Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 709
damon Avatar asked Oct 30 '12 14:10

damon


1 Answers

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

from django.db import models
Organization.objects.filter(models.Q(members=me) | models.Q(founder=me))
like image 152
Aidas Bendoraitis Avatar answered Oct 06 '22 10:10

Aidas Bendoraitis