Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
453 views
in Technique[技术] by (71.8m points)

python - Django - enforcing ManyToManyField unique items

I'm trying to do something simple like this:

members = models.ManyToManyField(User, blank=True, null=True, unique=True)

but unique isn't allowed. When looking at the table created, it makes foreign keys so uniqueness is implied I imagine.

I want to be able to associate members with this model representing a group. The group can have no members but I don't want the same member to be able to join the group twice.

My thought would be that an exception would be thrown if I try and do this but it seems that an exception is not thrown.

def join(request,id):
    user = request.user
    mygroup = Group.objects.get(id=id)
    mygroup.members.add(user)
    mygroup.num_members += 1
    mygroup.save()

num_members is incremented, because no exception is thrown. Duplicate users don't appear in the admin utility. Does add() fail silently? Should I just simply check if the user is contained already before adding?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For one, I wouldn't use num_members. Instead, you can check how many members there are with mygroup.members.count(). Secondly, adding members more than once doesn't really add them more than once, so you're fine.

A ManyToManyField on Group for member pointing to User is implemented with a separate table (something like group_group_users) which has a foreign key to Group and User. A user can have multiple groups, and a group can have multiple users, but there can't be two rows in group_group_users for the same relationship (ie, unique together foreign keys).

Usage:

>>> group = Group.objects.get(pk=1)
>>> user = User.objects.get(pk=1)
>>> group.members.add(user)
>>> # Worked fine as expected. Let's check the results.
>>> group.members.all()
[<User: foousername>]
>>> group.members.add(user)
>>> # Worked fine again. Let's check for duplicates.
>>> group.members.all()
[<User: foousername>]
>>> # Worked fine.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...