0

I have a Product and User model and I wanted to generate statistics of product view (idea is to implement view count). I have created a new model called ProductViewed and signal that gets fired whenever I make a get request to retrieve a single Product. I know how to get view count for each Product. However I wanted to make the statistics fair and I want to remove every view generated by the same user or IP address in one day.

product viewed model

class ProductViewed(models.Model):
    user = models.ForeignKey(
        get_user_model(), on_delete=models.CASCADE, blank=True, null=True, related_name="viewed")
    ip_address = models.CharField(max_length=255, blank=True, null=True)
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f'{str(self.product)} viewed on {self.created_at}'

    class Meta:
        ordering = ('-created_at', )
        verbose_name_plural = "ProductViewed"

Query that I am using is as follows:

ProductViewed.objects.filter(product_id=<someid>).count()

I want to achieve this

# before filtering
Pr1 viewed on 08.07.2020 by user1, Pr1 viewed on 08.07.2020 by user1, Pr1 viewed on  08.07.2020 by user2
# after filtering
Pr1 viewed on 08.07.2020 by user1, Pr1 viewed on 08.07.2020 by user2

Question: How to remove products viewed by the same user in a day?

Madiyor
  • 761
  • 9
  • 23

2 Answers2

1

you can use distinct(). You can add existing fields into values.

ProductViewed.objects.filter(product_id=<someid>).values("user", "ip_address", "created_at__date").distinct().count()
Madiyor
  • 761
  • 9
  • 23
Pruthvi Barot
  • 1,948
  • 3
  • 14
0

try this

ProductViewed.objects.filter(product_id=<someid>).values("user", "created_at__date").distinct().count()
Madiyor
  • 761
  • 9
  • 23
Jaydeep
  • 775
  • 2
  • 8
  • 14