See if user in ManyToManyField
<p>I am trying to see if the current user is in the <code>collaborators</code> m2m field, but keep getting an error saying: </p>

<p><code>Cannot query "John Doe": Must be "Company" instance.</code></p>

<p>Could someone help me out with the conditional statement please?</p>

<p><strong>models.py:</strong></p>

<pre><code>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)
</code></pre>

<p><strong>views.py:</strong></p>

<pre><code>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
</code></pre>

<p>Full docs is <a href="https://docs.djangoproject.com/en/1.10/topics/db/examples/many_to_many/" rel="nofollow">here</a></p>

<p>You can use</p>

<pre><code>if company.user == user or company.collaborators.filter(collaborators=user):
</code></pre>

<p>or </p>

<pre><code>if company.user == user or company.collaborators.filter(id=user.id):
</code></pre>

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

python django django-models django-views many-to-many