BobBrez
BobBrez

Reputation: 723

Django "through" model iteration

The answer to this may (and probably) already exists out there but I am having a tough time trying to come up what to look for.

I have three models: Person, Group, and Membership.

class Person(Contact):
    first_name = models.CharField(_('first name'), max_length=200, blank=True)
    last_name = models.CharField(_('last name'), max_length=200, blank=True)

class Organization(Contact):
    title = models.CharField(_('title'), max_length=200)
    members = models.ManyToManyField(Person, blank=True, through='Membership')

class Membership(models.Model):
    person = models.ForeignKey(Person)
    organization = models.ForeignKey(Organization)
    position = models.CharField(max_length=64, blank=True)

I'd like to get a list of people and have easy access the group that a person belongs to but its not a 1-to-1 relationship between Memberships and Person. It seems like the easiest way would be to create a method get_memberships within Person which would return the memberships, if any, that a person is associated with. Does this make sense and is it a reasonable practice to access this relationship from within the model this way or is there a better way to go about it?

Upvotes: 3

Views: 2651

Answers (1)

user257111
user257111

Reputation:

Yes.

Person.organization_set.all() should return the list of organisations to which the Person in question belongs. For each organisation in that set, you can then return their position, so:

p = Person.objects.get(id=personid)

for o in p.organization_set.all():
    # you have o and p, you should be able to find a unique m.
    m = Membership.objects.get(Person=p, Organization=o)

See the documentation here.

Upvotes: 6

Related Questions