I have a model that should have a group of users related to it.
Basically much like Django's Group. Now, normally this kind of
relation is easily done by puting in the user object a ManyToOne field
to the 'container' model. However, I don't actually have a User object
since I'm using the one provided by Django. Somy question is: how do I
accomplish that?
I thought of using a Group (the Django model) and then having a one to
one relationship in my container; but I think there's a much simpler
and elegant way.
Best regards,
Amit.
This is a good question, since you've thought almost all the way through
("I want to do this, I can't because...") and got all that analysis
correct. There's a solution. Actually there are two, related solutions,
depending upon how strict you want to be in your data modelling.
The simplest solution is to realise that a many-to-one is a restricted
case of many-to-many. So if you don't really want to enforce the
"one" (if it can be "many" -- so each user can be in multiple groups),
use a ManyToManyField on your Group model (I'll pretend your model is
called Group, just so I can type in code fragments).
Alternatively, if each User can only be in one group, you can model this
with a manual many-to-many field and the intermediate model includes
some uniqueness constraints:
class UserGroup(models.Model):
user = models.ForeignKey(User, unique=True)
group = models.ForeignKey("Group")
class Group(models.Model):
user = models.ManyToManyField(User, through=UserGroup)
...
The only tricky bit here is UserGroup.user having unique=True. That's
what constrains each user to belong to only a single group (read it as
"each user can only appear once in relation to the groups"). Thus,
you've achieved the desired model without modifying anything but models
entirely under your own control.
Regards,
Malcolm