考虑这个模型:
class pm_thread(models.Model):
subject = models.CharField(max_length=200)
participants = models.ManyToManyField(User)
Run Code Online (Sandbox Code Playgroud)
检查用户是否在 ManyToManyField 中的最佳方法是什么?例子:
thread = get_object_or_404(pm_thread, pk=thread_id)
if not thread.participants.contains(request.user):
return HttpResponse("403 FORBIDDEN",status=403)
Run Code Online (Sandbox Code Playgroud)
您可以使用in运算符:
if not request.user in thread.participants.all():
...
Run Code Online (Sandbox Code Playgroud)
小智 5
由于我无法在@Harmish 下发表评论,所以我必须指出,在 PEP8 标准下,会员资格应该是x not in而不是not x in
因此,您的代码如下所示:
if request.user not in thread.participants.all():
...
Run Code Online (Sandbox Code Playgroud)
来源:https : //www.python.org/dev/peps/pep-0008/#programming-recommendations
小智 5
其他答案调用.all(),它执行查询以检索关系中的所有对象(所有参与者),然后使用 Python 代码检查是否包含该用户。
更好的方法是使用过滤查询直接查询用户是否包含在关系中。
if not thread.participants.filter(id=request.user.id).exists():
return HttpResponse("403 FORBIDDEN",status=403)
Run Code Online (Sandbox Code Playgroud)
请注意,thread.paricipants它本身就是一个 Django QuerySet。
| 归档时间: |
|
| 查看次数: |
4687 次 |
| 最近记录: |