jape jape - 2 months ago 5
Python Question

See if user in ManyToManyField

I am trying to see if the current user is in the

collaborators
m2m field, but keep getting an error saying:

Cannot query "John Doe": Must be "Company" instance.


Could someone help me out with the conditional statement please?

models.py:

class MyUser():
name = ...
email = ...

class Company(models.Model):
user = models.ForeignKey(MyUser, null=True,
related_name='company_owner',
on_delete=models.SET_NULL)
collaborators = models.ManyToManyField(MyUser, blank=True,
related_name='company_collaborators')
name = models.CharField(max_length=120)


views.py:

def company_dash(request, username):
user = request.user
company = get_object_or_404(
Company, Q(is_active=True), username=username)

# NEED HELP HERE PLEASE
if company.user == user or company.collaborators.filter(company_collaborators=user).exists():
# do something

Answer

Full docs is here

You can use

if company.user == user or company.collaborators.filter(collaborators=user):

or

if company.user == user or company.collaborators.filter(id=user.id):

I think there is no need to add .exists() due to filter(collaborators=user) returns list that to be evaluated to be False if empty.