开发者

How to check for entity that haven't got attribute in table

开发者 https://www.devze.com 2023-01-10 23:27 出处:网络
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:

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 =开发者_StackOverflow社区 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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号