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

时间:2022-10-04 15:37:46

From the Django documentation...

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.

当您只处理简单的多对多关系时,例如混合和匹配披萨和配料,您只需要一个标准的ManyToManyField。然而,有时您可能需要将数据与两个模型之间的关系关联起来。

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.

例如,考虑应用程序跟踪音乐家所属的音乐组的情况。一个人与他们所属的组之间有一个多对多关系,所以你可以用一个许多的tomanyfield来表示这个关系。但是,关于您可能想要收集的成员关系有很多细节,比如这个人加入组的日期。

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:

对于这些情况,Django允许您指定用于管理多对多关系的模型。然后可以在中间模型上添加额外的字段。中间模型与ManyToManyField关联,通过参数指向作为中介的模型。对于我们的音乐家示例,代码看起来是这样的:

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:

既然您已经设置好了您的ManyToManyField来使用中间模型(这里是会员制),那么您就可以开始创建一些多对多的关系了。您可以通过创建中间模型的实例来实现这一点:

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()
[<Person: Ringo Starr>]

ringo.group_set.all()
[<Group: The Beatles>]

m2 = Membership.objects.create(person=paul, group=beatles,
...     date_joined=date(1960, 8, 1),
...     invite_reason= "Wanted to form a band.")

beatles.members.all()
[<Person: Ringo Starr>, <Person: Paul McCartney>]

source: http://docs.djangoproject.com/en/dev/topics/db/models/#intermediary-manytomany

来源:http://docs.djangoproject.com/en/dev/topics/db/models/ intermediary-manytomany

My question is, how do I set up my view and template to access these additional attributes. Say I have a band page and I want to display the band name, iterate through the membership records and display names and date_joined.

我的问题是,如何设置视图和模板来访问这些附加属性。假设我有一个带页面,我想要显示乐队名,遍历成员记录,并显示名称和date_join。

Should I pass a band object to the template? Or do I pass the membership objects somehow?

我应该将带对象传递给模板吗?或者我是否通过了会员对象?

And how would I create the for loops in in the template?

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

Thanks.

谢谢。

2 个解决方案

#1


34  

The easiest way is just to pass the band to the template. Templates are capable of navigating the relationships between models and there is both members and membership_set queryset managers on Group. So here is how I would do it:

最简单的方法就是将带传递给模板。模板能够导航模型之间的关系,并且在组中有成员和membership_set的queryset管理器。我是这样做的:

view:

观点:

def group_details(request, group_id):
    group = get_object_or_404(Group, pk=group_id)
    return render_to_response('group_details.html',
                              {'group': group})

template:

模板:

<h2>{{ group.name }}</h2>
{% for membership in group.membership_set.all %}
    <h3>{{ membership.person }}</h3>
    {{ membership.date_joined }}
{% endfor %}

#2


6  

I'm not sure whether it's only solution or not, but passing relation objects to the template certainly works. In your view, get QuerySet of Membership objects:

我不确定它是否是唯一的解决方案,但是将关系对象传递给模板肯定是有效的。在您的视图中,获取成员对象的查询集:

rel = Membership.objects.filter( group = your_group ).select_related()

and pass it to template, where you can iterate over it with {% for %}

然后将其传递给模板,在该模板中,您可以使用{% for %}对其进行迭代

{% for r in rel %}
     {{ r.person.name }} joined group {{ r.group.name }} on {{ r.date_joined }}<br />
{% endfor %}

Note that this should not perform any additional queries because of select_related().

注意,由于select_related(),不应该执行任何附加查询。

#1


34  

The easiest way is just to pass the band to the template. Templates are capable of navigating the relationships between models and there is both members and membership_set queryset managers on Group. So here is how I would do it:

最简单的方法就是将带传递给模板。模板能够导航模型之间的关系,并且在组中有成员和membership_set的queryset管理器。我是这样做的:

view:

观点:

def group_details(request, group_id):
    group = get_object_or_404(Group, pk=group_id)
    return render_to_response('group_details.html',
                              {'group': group})

template:

模板:

<h2>{{ group.name }}</h2>
{% for membership in group.membership_set.all %}
    <h3>{{ membership.person }}</h3>
    {{ membership.date_joined }}
{% endfor %}

#2


6  

I'm not sure whether it's only solution or not, but passing relation objects to the template certainly works. In your view, get QuerySet of Membership objects:

我不确定它是否是唯一的解决方案,但是将关系对象传递给模板肯定是有效的。在您的视图中,获取成员对象的查询集:

rel = Membership.objects.filter( group = your_group ).select_related()

and pass it to template, where you can iterate over it with {% for %}

然后将其传递给模板,在该模板中,您可以使用{% for %}对其进行迭代

{% for r in rel %}
     {{ r.person.name }} joined group {{ r.group.name }} on {{ r.date_joined }}<br />
{% endfor %}

Note that this should not perform any additional queries because of select_related().

注意,由于select_related(),不应该执行任何附加查询。