存在多对多关系中的对象

时间:2016-09-14 18:30:53

标签: django django-models model many-to-many

Python Django代码:

class UserGroup(models.Model):
    users = models.ManyToManyField(User)

    def __contains__(user):
        pass # What should be here?

User这是另一种模式。)

如何有效地检查用户是否属于"对给定的用户群?

1 个答案:

答案 0 :(得分:1)

您可以通过m2m经理查看:

def __contains__(self, user):
    return user in self.users.all() # return boolean

现在只需查看您的实例:

user = User.objects.get(pk=some_pk) 
group = UserGroup.objects.get(pk=some_pk)
# or use another queries to fetch instanses
if user in group:
    # do your logic