0

In my frontend application I have a panel which shows 6 the most popular products on my site. Searching for the most popular products each request by the number of views can be costly. I think that a good way to improve it will be to create a table in my data base which will store 6 the most popular products and the table will be refreshed for example every one minute. What should I looking for to do so cyclical operation on my django backend?

  • 2
    Does this answer your question? [Set up a scheduled job?](https://stackoverflow.com/questions/573618/set-up-a-scheduled-job) – May.D Nov 02 '21 at 11:32
  • Why not write an ajax request that update the top 6 product that you can save in the session – Rvector Nov 02 '21 at 11:33
  • 1
    you want to run a operation in perticular period so you use django cron for this cron is used to run perticular operation in fixed period here you will find how to use it https://django-cron.readthedocs.io/en/latest/installation.html – Vishal Pandey Nov 02 '21 at 11:54

1 Answers1

1

You can create separate model

models.py

class ProductRecord(models.Model):

    product = models.OneToOneField(
        'Product'
        related_name='stats', on_delete=models.CASCADE)

    # Data used for generating a score
    num_views = models.PositiveIntegerField(default=0)
    num_basket_additions = models.PositiveIntegerField(
        default=0)
    num_purchases = models.PositiveIntegerField(
        default=0)

    # Product score - used within search
    score = models.FloatField(default=0.00)

    def __str__(self):
        return _("Record for '%s'") % self.product

rule_engine.py

class Calculator:
    weights = {
        'num_views': 1,
        'num_basket_additions': 3,
        'num_purchases': 5
    }

    def calculate_scores(self):
        total_weight = float(sum(self.weights.values()))
        weighted_fields = [
            self.weights[name] * F(name) for name in self.weights.keys()]
        ProductRecord.objects.update(
            score=sum(weighted_fields) / total_weight)

receivers.py

Here you'll have multiple signals to receive addition to basket, views, favoriting, and so on..

This is an example

def receive_product_view(sender, product, user, **kwargs):
   UserProductView.objects.create(product=product, user=user)
   ## yyou can do much advanced staff here using signals 

Another solution

You can use Redis to save such these data like counts and purchases Or make aws lambda function for receiving analytical data, all of these solutions depend on your case

This is a pseudo solution. hope it's been beneficial to you

A.Raouf
  • 2,171
  • 1
  • 24
  • 36