Django check if object in ManyToMany field

DjangoDjango ModelsDjango Views

Django Problem Overview


I have quite a simple problem to solve. I have Partner model which has >= 0 Users associated with it:

class Partner(models.Model):
    name = models.CharField(db_index=True, max_length=255)
    slug = models.SlugField(db_index=True)
    user = models.ManyToManyField(User)

Now, if I have a User object and I have a Partner object, what is the most Pythonic way of checking if the User is associated with a Partner? I basically want a statement which returns True if the User is associated to the Partner.

I have tried:

users = Partner.objects.values_list('user', flat=True).filter(slug=requested_slug)
if request.user.pk in users:
    # do some private stuff

This works but I have a feeling there is a better way. Additionally, would this be easy to roll into a decorator, baring in mind I need both a named parameter (slug) and a request object (user).

Django Solutions


Solution 1 - Django

if user.partner_set.filter(slug=requested_slug).exists():
     # do some private stuff

Solution 2 - Django

If we just need to know whether a user object is associated to a partner object, we could just do the following (as in this answer):

if user in partner.user.all():
    #do something

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDarwin TechView Question on Stackoverflow
Solution 1 - DjangoPeter DeGlopperView Answer on Stackoverflow
Solution 2 - DjangoAnupamView Answer on Stackoverflow