检查项目是否在ManyToMany字段中?

问题描述 投票:2回答:2

考虑这个模型:

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)
python django
2个回答
3
投票

您可以使用in运算符:

if not request.user in thread.participants.all():
    ...

0
投票

由于我无法在@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

© www.soinside.com 2019 - 2024. All rights reserved.