Python Django代码:
class UserGroup(models.Model):
users = models.ManyToManyField(User)
def __contains__(user):
pass # What should be here?
(User
这是另一种模式。)
如何有效地检查用户是否属于"对给定的用户群?
答案 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