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.
- [Django]-Saving post from tweepy to django model in a good way
- [Django]-How to query for distinct groups of entities which are joined via a self-referential many-to-many table?
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
- [Django]-Programatically populate sample data for Django Image/File fields?
- [Django]-Accessing user home directory from django
- [Django]-Django-storages S3Boto3Storage makes HEAD and GET requests on read
- [Django]-Django formset if TOTAL_FORMS has different number than actual number of forms
- [Django]-How to authenticate users with HttpOnly Cookie Django-React
Source:stackexchange.com