Django - using intermediate user group model

435 views
Skip to first unread message

Fernando Balmaceda

unread,
Sep 21, 2018, 2:16:05 PM9/21/18
to Django users
Hi everyone!

I am trying to add a foreign key in a model to the table intermediary between User and Group. Something like this:

from django.db import models
from django.contrib.auth.models import User


class Enrollment(models.Model):
   
    user_groups
= models.ForeignKey(User.groups.through, on_delete=models.CASCADE)

But when i try this, django throws an error:

core.Enrollment.user_groups: (fields.E300) Field defines a relation with model 'User_groups', which is either not installed, or is abstract.

How can I achieve this?. 
Using Django 2.0

Thanks!

Mateusz

unread,
Sep 23, 2018, 1:19:45 PM9/23/18
to Django users
Is that User [N] -- [N] Group with many to many through Enrollment (something like that: User [1] -- [N] Enrollment [N] -- [1] Group)? Then, the answer in this gist here.

Fernando Balmaceda

unread,
Sep 24, 2018, 1:18:26 PM9/24/18
to Django users
Thanks for the answer Mateusz, but i need the original intermediate between User and Groups. i don't need to create my custom group model

Mateusz

unread,
Sep 24, 2018, 2:56:31 PM9/24/18
to Django users
I still doubt if I understood correctly, but if yes -- https://docs.djangoproject.com/en/2.1/topics/db/examples/many_to_many/ contains your answer. Either you don't need 'through' table (because it would not carry any additional data), or if you do... you can just add only foreign keys to 'User' and 'Group' to your Enrollment model, but then access is a bit different.

# models.py
class User(models.Model):
   
# things that normally belongs there

class Group(models.Model):
   
# things that normally belongs there

class Enrollment(models.Model):
   
group = models.ForeignKey(Group, on_delete=models.CASCADE, related_name='contains_users')
    user
= models.ForeignKey(User, on_delete=models.CASCADE, related_name='in_group')

And access (you can use single filtering):
models.Enrollment.objects.filter(group=..., user=...)
or via related name (not tested):
models.User.in_group_set.all()
models
.Group.contains_users_set.all()
(more on related_name on Stack)
Reply all
Reply to author
Forward
0 new messages