2014-01-05 92 views
0

考慮這一模式:檢查項目是否在ManyToMany字段?

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) 

回答

1

可以使用in操作:

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

錯誤:'類型的參數 'ManyRelatedManager' 不iterable' – Jeremy

+0

啊,對'thread.participants.all()'來獲得QuerySet – Hamish

+0

現在可以使用,謝謝! – Jeremy