5
Django文档给出this关联额外数据与M2M关系的示例。虽然这很简单,但现在我试图在视图中使用额外的数据,但感觉非常笨拙(通常意味着“我做错了”)。使用django的“额外字段”与额外字段的多对多关系
例如,使用链接的文档中定义的模型上面,我可以做到以下几点:
# 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(组= band.pk)” 位。我对这件事做错了吗?
现在说我想在加入特定乐队的日期(比如说beatles)中订购人员,是否有任何order_by子句可以放在Person.objects.all()上,让我这样做?
任何意见将不胜感激。
感谢您的回答。当然,这回答了我问的问题,但是通过反思,我意识到我提出了错误的问题。我又试图解释问题空间[这里] [1]。干杯。 [1]:http://stackoverflow.com/questions/1291889/is-a-many-to-many-relationship-with-extra-fields-the-right-tool-for-my-job – whichhand 2009-08-18 05:08:16
Lesson# 2:评论不接受标记。 – whichhand 2009-08-18 05:11:48