python多对多word模板_python – 如何从django模板访问多对多“通过”表的属性?

从Django文档…

When you’re only dealing with simple many-to-many relationships such as mixing and matching pizzas and toppings, a standard ManyToManyField is all you need. However, sometimes you may need to associate data with the relationship between two models.

For example, consider the case of an application tracking the musical groups which musicians belong to. There is a many-to-many relationship between a person and the groups of which they are a member, so you could use a ManyToManyField to represent this relationship. However, there is a lot of detail about the membership that you might want to collect, such as the date at which the person joined the group.

For these situations, Django allows you to specify the model that will be used to govern the many-to-many relationship. You can then put extra fields on the intermediate model. The intermediate model is associated with the ManyToManyField using the through argument to point to the model that will act as an intermediary. For our musician example, the code would look something like this:

class Person(models.Model):

name = models.CharField(max_length=128)

def __unicode__(self):

return self.name

class Group(models.Model):

name = models.CharField(max_length=128)

members = models.ManyToManyField(Person, through='Membership')

def __unicode__(self):

return self.name

class Membership(models.Model):

person = models.ForeignKey(Person)

group = models.ForeignKey(Group)

date_joined = models.DateField()

invite_reason = models.CharField(max_length=64)

Now that you have set up your ManyToManyField to use your intermediary model (Membership, in this case), you’re ready to start creating some many-to-many relationships. You do this by creating instances of the intermediate model:

ringo = Person.objects.create(name="Ringo Starr")

paul = Person.objects.create(name="Paul McCartney")

beatles = Group.objects.create(name="The Beatles")

m1 = Membership(person=ringo, group=beatles,

... date_joined=date(1962, 8, 16),

... invite_reason= "Needed a new drummer.")

m1.save()

beatles.members.all()

[]

ringo.group_set.all()

[]

m2 = Membership.objects.create(person=paul, group=beatles,

... date_joined=date(1960, 8, 1),

... invite_reason= "Wanted to form a band.")

beatles.members.all()

[, ]

source: 07000

我的问题是,如何设置我的视图和模板来访问这些额外的属性。说我有一个乐队页面,我想显示乐队名称,遍历成员记录和显示名称和date_joined。

我应该传递一个band对象到模板?还是我通过成员资格对象不知何故?

如何在模板中创建for循环?

谢谢。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值