带有prefetch_related的Django查询

时间:2018-07-13 17:18:48

标签: django

我正在努力从预取相关的查询中获取所需的数据。

我有一个事件表(日历表),一个成员表和一个将两者链接在一起的与会者表。

我的模型如下:

class Member(models.Model):
    firstname = models.CharField(max_length=40)
    lastname = models.CharField(max_length=50)
    email = models.EmailField(blank=True, verbose_name ='e-mail')
    phone = models.CharField(max_length=40)
    membershipnum = models.CharField(max_length=40)

class Attendee(models.Model):
    memberid = models.ForeignKey(Member, on_delete=models.SET(0), related_name="attendingmembers")
    calendarid = models.ForeignKey(Calendar, on_delete=models.SET(0))
    attended =  models.BooleanField(default=0)
    paid =  models.BooleanField(default=0)
    class Meta:
        db_table = 'attendee' 

对于特定事件,我想要一个与会者列表,以及与会者表中的“有人参加”和“付费”字段。

我认为我有

attendees = Member.objects.filter(attendingmembers__calendarid_id=id).prefetch_related('attendingmembers') 

我找到了合适的成员,但是我不知道这是否是最好的方法?而且我不知道如何到达与会者字段。

如果我愿意

for thisone in attendees:
        print(thisone)
        print(thisone.attendingmembers)

我从第一张纸上得到了预期的收益,但是第二张纸给了我 myapp.Attendee.None

任何建议都值得赞赏。

1 个答案:

答案 0 :(得分:0)

您仍然需要.all()来获取您的亲戚项目列表:

for this one in attendees:
    print(thisone.attendingmembers.all())

顺便说一句,您是要获得全部attendingmembers还是仅获得具有正确权限的calendar_id的那些硬币?

attendees = Member.objects.filter(attendingmembers__calendar_id=id).prefetch_related('attendingmembers')
# return all Members having at least one attendingmember with calendar_id=id, and prefetch all of their attendingmembers

attendees = Member.objects.filter(attendingmembers__calendar_id=id).prefetch_related(Prefetch('attendingmembers', queryset=Attendee.objects.filter(calendar_id=id)))
# return all Members  having at least one attendingmember with calendar_id=id, and prefetch their attendingmembers matching the filter

The documentation向您展示如何在Prefetch对象中使用to_attr参数;)