Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing many-to-many set field in django relation

I have a set of models similar to that below, where a person can be a member of many clubs, but have a different membership type. In this instance, I consider Membership to be a weak entity of Club

class Person(models.Model):
    name = models.TextField()

class Club(models.Model):
    members = models.ManyToManyField(
            Person,
            related_name="clubs"
            through='Membership'
            )

class Membership(models.Model):
    person = models.ForeignKey(Person)
    club = models.ForeignKey(Club)
    member_type = models.TextField()

I know that I can access the membership details from a club by going:

instance_of_club.membership_set.all()

And I can get a listing of all the people by using this:

instance_of_club.membership_set

However, I am trying to write a serialiser for this sort of scenario and am having trouble correctly finding the "membership" details from the django Meta class.

Club._meta.many_to_many gives the members field:

<django.db.models.fields.related.ManyToManyField: members>

But nothing on members gives any indication on how to get the _set accessor - and I need to be able to get these programatically. What I want is to be able to get a list of all ManyToMany through relations, and then get the objects these hold and not just the foreign objects.

For context:

  • members.related.through gives the Membership class, but not a collection of instances
  • members.related.related_name gives nothing
  • Club._meta.get_all_field_names() gives membership in the list, but not membership_set

How can I get a list of the through relation objects on a ManyToMany field?


1 Answers

Your Club model should probably look like:

class Club(models.Model):
    members = models.ManyToManyField(
        Person, related_name='clubs', through='Membership'
    )

I know that I can access the membership details from a club by going:

instance_of_club.membership_set.all()

And I can get a listing of all the people by using this:

instance_of_club.membership_set

This is not true! instance_of_club.membership_set is a club's related manager for the Membership model. instance_of_club.membership_set.all() is this related manager's QuerySet (too, of Membership model instances):

club_instance.members.all()  # all related Person instances of a club
club_instance.membership_set.all()  # all related Memberships of a club
person_instance.clubs.all()  # all related Club instances of a person
person_instance.membership_set.all()  # all related Memberships of a person
like image 134
user2390182 Avatar answered Jan 19 '26 18:01

user2390182



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!