简体   繁体   中英

Backwards many-to-many relationship with Proxy models in Django

I have a model name 'Group' with a ManyToMany relationship with the Django User, and a 'Membership' table between.

class UserManager(models.Manager):get_query_set(self):
        return super(UserManager, self).get_query_set().select_related('expenses')

class User(DjangoUser):
    objects = UserManager()
    class Meta:
        proxy = True

class Group(models.Model):
    name = models.CharField(verbose_name=_('Name'), max_length=255)
    users = models.ManyToManyField(User, related_name='groups', through='Membership')

class Membership(models.Model):
    user = models.ForeignKey(User)
    group = models.ForeignKey(Group)
    date_joined = models.DateField(auto_now_add=True, verbose_name=_('Date joined'))

When I try to get the groups for a user, everything is fine:

>>> User.objects.get(id=2).groups.all()    
[<Group: Group object>]
>>> User.objects.get(id=2).groups.get(id=1)
<Group: Group object>

The problem is that I can't get the users for a group:

>>> Group.objects.get(id=1).users.all()    
[]

The one thing I noticed is that the field 'user_id' in my database (generated by django) does not have the foreign key for the auth_user table, but the 'group_id' field has the foreign key for the myapp_group table.

Thanks in advance.

EDIT:

There is clearly something wrong here:

>>> User.objects.get(id=2).groups.get(id=1).users.all()    
[]

This is unfortunately a documented bug in the Django ORM. You will find more information about it here:

https://code.djangoproject.com/ticket/17299

The best alternative is to simply point to the default model. Since both save to the same place in the database, you can "convert" the returned models from auth.models.User to your proxy user model using the following technique . Make sure you use the one that doesn't hit your database a second time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM