0

say I have a model like this:

class Arrival(models.Model):
    client = models.ForeignKey(User, related_name='client')
    time = models.DateTimeField()

Now I would like to plot a graph with number of unique client visits at each date.

My current approach is to use:

Arrival.objects.values('client','time')

afterwards convert all the datetime field to a date field. Use python library to get a list of unique date, and then iterate through the clients to find out how many clients visit per date.

Do anyone have a more efficient approach please?

user1819047
  • 667
  • 9
  • 18

1 Answers1

1

Reposting my answer here:

Get daily counts of objects from Django

(Arrival.objects
    # get specific dates (not hours for example) and store in "created" 
    .extra({'created':"date(time)"})
    # get a values list of only "created" defined earlier
    .values('created')
    # annotate each day by Count of Arrival objects
    .annotate(created_count=Count('id')))
Community
  • 1
  • 1
Yuji 'Tomita' Tomita
  • 115,817
  • 29
  • 282
  • 245
  • Hey there, thanks a lot for the comment. But I think this thing does not filter out the duplicate visits. What method would you recommend to only count those ids which are unique? – user1819047 Jan 21 '15 at 01:18
  • how are you defining uniqueness. You want to count visits per day but once per client? – Yuji 'Tomita' Tomita Jan 21 '15 at 18:20