tags:

views:

26

answers:

1

In my application I need to check up on people's attendance and I want to know who hasn't attended two or more meetings. I have the following models:

class Talk(models.Model):
    title = models.CharField(max_length=200, primary_key=True)
    speaker = models.CharField(max_length=200)
    date_of_talk = models.DateField('date_of_talk')

    def __unicode__(self):
        return self.title

class Member(models.Model):
    name = models.CharField(max_length=200)
    talks = models.ManyToManyField(Talk, through='Event_Attendance')

    def __unicode__(self):
        return self.name

class Event_Attendance(models.Model):
    talk = models.ForeignKey('Talk')
    membersAttended = models.ForeignKey('Member')

As you can see I keep track of all the members attending talks.

My thoughts on how to find the members that haven't attended was to get all the members then iterating through them to find out whether or not they are in the Event_Attendance table. Is this the best approach or does Django have a method to already do this?

+2  A: 

Try:

Member.objects.annotate(talks_attended = Count('Event_Attendance')).filter(talks_attended__lt = 2)

This is untested, but I think is right. This will hopefully return you a QuerySet containing only those members who have not attended at least two talks.

You might find the documentation on Aggregation instructive.

Dominic Rodger
Thanks for the answer. Still reading around Aggregation to get an idea about what is going on so I can it to work thanks for the starting point.
Dean
Have a working solution: `Member.objects.annotate(talks_attended = Count('talks')).filter(talks_attended__lt = 2)` Now need to adapt this so i can develop it to find the two latest talks. Thanks very much :)
Dean