考虑这个模型:
class pm_thread(models.Model):
subject = models.CharField(max_length=200)
participants = models.ManyToManyField(User)
检查用户是否在ManyToManyField中的最佳方法是什么?例:
thread = get_object_or_404(pm_thread, pk=thread_id)
if not thread.participants.contains(request.user):
return HttpResponse("403 FORBIDDEN",status=403)
您可以使用in
运算符:
if not request.user in thread.participants.all():
...
由于我无法在@Harmish下发表评论,我必须指出,根据PEP8标准,成员资格应该是x not in
而不是not x in
因此,您的代码看起来像:
if request.user not in thread.participants.all():
...
资料来源:https://www.python.org/dev/peps/pep-0008/#programming-recommendations