damon
damon

Reputation: 8477

is it possible to query with a logical OR in django

I have a model 'Organization' which has following fields

class Organization(models.Model):
    members = models.ManyToManyField(User,related_name='org_members')
    title = models.CharField(max_length=200)
    description = models.TextField()
    founder = models.ForeignKey(User,related_name='org_founder')
    def __unicode__(self):
        return self.title

To make a query to get all orgs where a user is a member

me=User.objects.get(username='damon')
Organization.objects.filter(members=me)

Similarly To make a query to get all orgs where a user is a founder

Organization.objects.filter(founder=me)

I want to write a query which will fetch me all orgs in which a user is a member or courses for which he is the founder.

I tried this as below

Organization.objects.filter(members=me or founder=me)

This causes Invalid Syntax error

Can someone tell me how to make this query

Upvotes: 6

Views: 6258

Answers (3)

Aidas Bendoraitis
Aidas Bendoraitis

Reputation: 4003

To query with a logical OR, you need to use the Q objects (docs):

from django.db import models
Organization.objects.filter(models.Q(members=me) | models.Q(founder=me))

Upvotes: 17

Traian
Traian

Reputation: 3003

from django.db.models import Q
Organization.objects.filter(Q(members='me') | Q(founder='me'))

Upvotes: 4

Mikael
Mikael

Reputation: 3236

Use Q objects. That will help you with what you are after.

Upvotes: 2

Related Questions