How to access fields in a many-to-many custom object in templates

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 custom entity with multiple entities with additional fields.
If I have an instance of a person, how can I access the corresponding date_joined fields of all of his memberships, both in regular code and in the django template file?

+7
django django-models many-to-many has-many-through
source share
1 answer

person.membership_set.all() will provide you with a list of all Membership instances for the given person . You can use this in both regular code and template.

 for each in person.membership_set.all(): print each.date_joined {% for each in person.membership_set.all %} {{ each.date_joined }} {% endfor %} 
+10
source share

All Articles