Python 如何从 Django 模板访问多对多“直通”表的属性?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3368442/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 10:40:59  来源:igfitidea点击:

How do I access the properties of a many-to-many "through" table from a django template?

pythondjangodjango-templatesmany-to-manyrelationship

提问by Alex

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.

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:

当您只处理简单的多对多关系(例如混合和匹配比萨饼和配料)时,标准的 ManyToManyField 就是您所需要的。但是,有时您可能需要将数据与两个模型之间的关系相关联。

例如,考虑一个跟踪音乐家所属音乐团体的应用程序的情况。一个人和他们所属的组之间存在多对多关系,因此您可以使用 ManyToManyField 来表示这种关系。但是,您可能希望收集许多关于成员资格的详细信息,例如此人加入群组的日期。

对于这些情况,Django 允许您指定将用于管理多对多关系的模型。然后,您可以在中间模型上放置额外的字段。中间模型与 ManyToManyField 相关联,使用 through 参数指向将充当中介的模型。对于我们的音乐家示例,代码如下所示:

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_joined。

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.

谢谢。

采纳答案by Rory Hart

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:

最简单的方法就是将带区传递给模板。模板能够导航模型之间的关系,并且 Group 上有 members 和 members_set 查询集管理器。所以这是我将如何做到的:

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 %}

回答by cji

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:

我不确定这是否只是解决方案,但将关系对象传递给模板肯定有效。在您看来,获取 Membership 对象的 QuerySet:

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().

回答by Quique

Rory Hart's answer is mostly correct. It allows you to use intermediate (through) table in the ManyToMany relationship.

罗里哈特的回答大部分是正确的。它允许您through在多对多关系中使用中间 ( ) 表。

However, the loop in the template should be modified using select_relatedas cji suggests, in order to avoid hitting the database with additional queries:

但是,模板中的循环应该select_related按照 cji 的建议进行修改,以避免使用其他查询访问数据库:

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