Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Django: Count number of times object appears in Foreign Key with filter

My models are as so:

class TeamMember(models.Model):
    name = models.CharField(max_length=500)
    

class Opportunity(models.Model):
     name = models.CharField(max_length=500)
     date_created = models.DateTimeField(
        auto_now=True)
     team_lead = models.ForeignKey('TeamMember', blank = False, related_name = 'lead_opps')

I need to create a list of team member names with the number of opportunities they have taken part of ordered by the count. This is straightforward using the method below, however- I also need to limit the opportunities by date range.

So to summarize, I need to create a list of team members with the number of opportunities they have taken lead on within a time range. How do I add a filter to the opps being counted within the annotation?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Here is what I have so far:

TeamMember.objects.annotate(num_opps = Count('lead_opps')).order_by('-num_opps')[0].num_opps

>Solution :

Please RTFM.

You are looking for this bit of documentation:

... .annotate(...) \
    .filter(date_created__gt=start) \
    .filter(date_created__lt=end) \
    .order_by ...
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading