Search code examples
python-3.xdjangodjango-modelsmany-to-many

Accessing the values of a ManyToManyField in Django


I've created a Many to Many relationship in my project like this:

class CustomUser(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(_('Email Address'), unique=True)
    user_name = models.CharField(_('User Name'), max_length=150, unique=True)
    # and a lot of other fields and stuff


class Course(models.Model):
    user = models.ManyToManyField(CustomUser, related_name="enrollments", blank=True, null=True)
    course_name = models.CharField(_("Course Name"), max_length=200)

In Django Admin site, I created some courses and added users to it. What I need is to get a list of courses that a unique user is enrolled and a list of users enrolled in a unique course.

I know that I can access the Related Manager like this:

user.enrollments

<django.db.models.fields.related_descriptors.create_forward_many_to_many_manager.<locals>.ManyRelatedManager object at 0x7f4df159c0a0>

And I know also that I can access the intermediate m2m class using:

user.enrollments.through

<class 'core.models.Course_user'>

What I could not get (or find in the docs or even in internet at all) is how I can access the values contained in this relation (courses a user is enrolled and users enrolled in a course).

Any help will be appreciated.


Solution

  • user.enrollments is a manager, just like Course.objects is a manager. You can create a QuerySet of the objects by using the .all() method [Django-doc]:

    user.enrollments.all()  # collection of Courses user is enrolled in

    and we can query for the users enrolled in a Course object course:

    course.user.all()  # users enrolled in course