python - 如何从 django 模板访问多对多 "through"表的属性?

标签 python django django-templates many-to-many relationship

来自 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()
[<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

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

我应该将带对象传递给模板吗?还是我以某种方式传递成员资格对象?

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

谢谢。

最佳答案

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

查看:

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

模板:

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

关于python - 如何从 django 模板访问多对多 "through"表的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3368442/

相关文章:

python - Python 中仅当不为 null 时才打印 - 一行方法?

python - 检查是否有与输入图像完全相同的图像

python - 如何判断已安装模块中有哪些方法可用

django - 如何限制用户使用浏览器 "back button"返回上一页(改为重定向到不同的页面)?

django - 如何在Django ORM中的FROM子句中获取子查询

python - 覆盖 DRF 中序列化程序的数据属性

django - 如何使必填字段错误消息在 Django 中第一次不显示

Python Flask "send_file()"方法类型错误

jquery - Django : Update div with AJAX

django - forloop.last 在 Django 中不起作用