14

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?

tshepang
  • 12,111
  • 21
  • 91
  • 136
Jonathan Livni
  • 101,334
  • 104
  • 266
  • 359

1 Answers1

17

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 %}
Manoj Govindan
  • 72,339
  • 21
  • 134
  • 141
  • Can you show the view? Consists the dictionary as argument for the render function only of person? Why is the membership_set function written in lower case when the Class Membership is upper? – Timo May 02 '14 at 18:58
  • because lower case is the convention – stats con chris Oct 19 '22 at 14:03