Django文档给出this将额外数据与M2M关系相关联的示例。虽然这很简单,但现在我试图在我的视图中使用额外的数据,它感觉非常笨拙(这通常意味着“我做错了”)。
例如,使用上面链接文档中定义的模型,我可以执行以下操作:
# Some people
ringo = Person.objects.create(name="Ringo Starr")
paul = Person.objects.create(name="Paul McCartney")
me = Person.objects.create(name="Me the rock Star")
# Some bands
beatles = Group.objects.create(name="The Beatles")
my_band = Group.objects.create(name="My Imaginary band")
# The Beatles form
m1 = Membership.objects.create(person=ringo, group=beatles,
date_joined=date(1962, 8, 16),
invite_reason= "Needed a new drummer.")
m2 = Membership.objects.create(person=paul, group=beatles,
date_joined=date(1960, 8, 1),
invite_reason= "Wanted to form a band.")
# My Imaginary band forms
m3 = Membership.objects.create(person=me, group=my_band,
date_joined=date(1980, 10, 5),
invite_reason= "Want to be a star.")
m4 = Membership.objects.create(person=paul, group=my_band,
date_joined=date(1980, 10, 5),
invite_reason= "Wanted to form a better band.")
现在,如果我想要打印一个简单的表格,每个人都会给出他们加入每个乐队的日期,目前我正在这样做:
bands = Group.objects.all().order_by('name')
for person in Person.objects.all():
print person.name,
for band in bands:
print band.name,
try:
m = person.membership_set.get(group=band.pk)
print m.date_joined,
except:
print 'NA',
print ""
感觉非常难看,特别是“m = person.membership_set.get(group = band.pk)”位。我这整件事都错了吗?
现在说我想按照他们加入特定乐队的日期(比如披头士乐队)订购人们是否有任何order_by子句我可以放在Person.objects.all()上让我这样做?
非常感谢任何建议。
答案 0 :(得分:3)
您应该查询成员资格模型:
members = Membership.objects.select_related('person', 'group').all().order_by('date_joined')
for m in members:
print m.band.name, m.person.name, m.date_joined
在这里使用select_related我们避免了1 + n查询问题,因为它告诉ORM进行连接并在一个查询中选择所有内容。