[Answer]-Django: What is the most efficient method to query and aggregate based on date + foreign key

1👍

Model Description

class Foo(models.Model):
  post_date = models.DateTimeField()
  related = models.ForeignKey(Related)

related_info = Foo.objects.filter(post_date__get=start_date, \
    post_date__lte = end_date).extra(select = {'temp_date':'date(post_date)'}). \
    values('temp_date').annotate(count = Count('related'))


#related_info is [('post_date','related_count'),...]

0👍

You can use Q objects

With that definition

class Foo(models.Model):
  date = models.DateTimeField()
  related = models.ForeignKey(Related, related_name="foos")

#1)
objects = Foo.objects.filter(Q(date__gte=start) & Q(date__lte=end))

#2)
related = Related.objects.filter(foos__in=objects)
count = related.count()

Please, test it and tell me.

Leave a comment