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
CodePudding user response:
Please RTFM.
You are looking for this bit of documentation:
... .annotate(...) \
.filter(date_created__gt=start) \
.filter(date_created__lt=end) \
.order_by ...