0

So let's say I have these 2 models:

class User(models.Model):
    name = models.CharField()
    dob = models.DateField()


class Product(models.Model):
    user = ForeignKey(User)
    created = models.DateTimeField()
    name = models.CharField()
    amount = models.DecimalField()

Users can create a product, and it will save when that product is created. What I want to ask is, is it possible to count the number of users that have a product within a range of time?

I'm using GenericViewSet for the views and created actions inside it to return the data. I want the views to return a data that looks like this:

{
    'data': [{
        'date': "2020-01-01",
        'total_users': 10
    }, {
        'date': "2020-01-02",
        'total_users': 17
    }]
}

I understand that I can filter the products using a date range like this to get the products:

Product.objects.filter(created__range=["2020-01-01", "2020-02-01"])

But how do I calculate the total users that have a product within that range? Is it possible to do annotations for this? Thanks in advance for your help!

karxav
  • 45
  • 1
  • 5

1 Answers1

0
from django.db import Count

Product.objects.filter(
    created__range=("2020-01-01", "2020-02-01")
).values(
    date=F('created')
).annotation(
    total_users=Count('user__id')
)
  • Hi! Thanks for your answer. I want to ask again, is it possible to calculate it like this? So User A have 2 products within 2020-01-01 - 2020-02-01, and User B have 3 products within 2020-01-01 - 2020-02-01, but the total user is only 2? – karxav Oct 06 '20 at 00:49