Monday, September 24, 2018

Re: Django - using intermediate user group model

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)


W dniu poniedziałek, 24 września 2018 19:18:26 UTC+2 użytkownik Fernando Balmaceda napisał:
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

El domingo, 23 de septiembre de 2018, 14:19:45 (UTC-3), Mateusz escribió:
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.


W dniu piątek, 21 września 2018 20:16:05 UTC+2 użytkownik Fernando Balmaceda napisał:
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!

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/7b669281-15d7-48ce-8c49-5e63fe159ca2%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment