C
C
Cyril2014-05-17 08:28:44
Django
Cyril, 2014-05-17 08:28:44

How to correctly compose a query for ManyToMany in Django?

No matter how much I read the documentation, I can't work properly with ORM and ManyToMany. I'm trying to request a list of groups in which the user is located.

class User(AbstractUser):
    ...

class Group(models.Model):
    ...
    Member_list = models.ManyToManyField(User, through='Member', related_name="Member_list")

class Member(models.Model):
    group = models.ForeignKey(Group)
    user = models.ForeignKey(User)
    ...

tried:
user = request.user
groups = user.group_set.all() - gives an empty list
member = user.member_set.all() - gives one link

Answer the question

In order to leave comments, you need to log in

3 answer(s)
C
Cyril, 2014-05-17
@aeHarkonnen

Hooray! Found a way to do this:

e = self.request.user
e.Member_list.all()
# output: [<Group: Group object>]

Or even simpler:
Like this :) I suspected that related_name was set for a reason, but the description was incomprehensible.

P
Pavel Solovyov, 2014-05-17
@pavel_salauyou

I don’t quite understand what you should have, but if the user should be in a group, then you need to

class User(AbstractUser):
    groups = models.ManyToManyField(User, through='Group')

after
user = request.user
groups = user.groups.all()

D
denizen, 2014-05-17
@denizen

You get a redundant model: the Member class is completely redundant. many-to-many can be done immediately for the User<->Group relation. And a sql table like your Member class will be made in Django ORM automatically.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question