[Django]-Check if item is in ManyToMany field?

8👍

You can use the in operator:

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

10👍

Other answers call .all(), which does a query to retrieve all objects in the relationship (all participants), and then uses Python code to check if the user is included.

A better approach would be to query whether the user is included in the relationship directly, using a filtered query.

if not thread.participants.filter(id=request.user.id).exists():
    return HttpResponse("403 FORBIDDEN",status=403)

Note that thread.paricipants is a Django QuerySet in and of itself.

5👍

Since I can’t comment under @Harmish, I’ll have to point that under the PEP8 standard, membership should be x not in and not not x in

Therefore, your code would look like:

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

Source: https://www.python.org/dev/peps/pep-0008/#programming-recommendations

Leave a comment