ChicagoMG2022
ChicagoMG2022

Reputation: 43

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?

Here is what I have so far:

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

Upvotes: 1

Views: 38

Answers (1)

J_H
J_H

Reputation: 20425

Please RTFM.

You are looking for this bit of documentation:

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

Upvotes: 1

Related Questions