How to access fields in a customized many-to-many through object in templates

依然范特西╮ 提交于 2019-12-19 05:17:41

问题


Consider the following models:

class Person(models.Model):
    name = models.CharField(max_length=128)

class Group(models.Model):
    name = models.CharField(max_length=128)
    members = models.ManyToManyField(Person, through='Membership')

class Membership(models.Model):
    person = models.ForeignKey(Person)
    group = models.ForeignKey(Group)
    date_joined = models.DateField()
    invite_reason = models.CharField(max_length=64)

Membership is a customized many-to-may through object with extra fields.
If I have a person instance, how can I access the corresponding date_joined fields of all its membership relations - both in regular code and in a django template file?


回答1:


person.membership_set.all() will give you a list of all Membership instances for a given person. You can use this in regular code as well as in the template.

for each in person.membership_set.all():
    print each.date_joined

{% for each in person.membership_set.all %}
    {{ each.date_joined }}
{% endfor %}


来源:https://stackoverflow.com/questions/3534708/how-to-access-fields-in-a-customized-many-to-many-through-object-in-templates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!