Django documentation

19. OR lookups

These docs are frozen for Django version 0.91. For current documentation, go here.

To perform an OR lookup, or a lookup that combines ANDs and ORs, use the complex keyword argument, and pass it an expression of clauses using the variable django.core.meta.Q.

Model source code

from django.core import meta

class Article(meta.Model):
    headline = meta.CharField(maxlength=50)
    pub_date = meta.DateTimeField()
    class META:
       ordering = ('pub_date',)

    def __repr__(self):
        return self.headline

API reference

Article objects have the following methods:

  • delete()
  • get_next_by_pub_date()
  • get_previous_by_pub_date()
  • save()

Sample API usage

This sample code assumes the above model has been saved in a file examplemodel.py.

>>> from django.models.examplemodel import articles

>>> from datetime import datetime
>>> from django.core.meta import Q

>>> a1 = articles.Article(headline='Hello', pub_date=datetime(2005, 11, 27))
>>> a1.save()

>>> a2 = articles.Article(headline='Goodbye', pub_date=datetime(2005, 11, 28))
>>> a2.save()

>>> a3 = articles.Article(headline='Hello and goodbye', pub_date=datetime(2005, 11, 29))
>>> a3.save()

>>> articles.get_list(complex=(Q(headline__startswith='Hello') | Q(headline__startswith='Goodbye')))
[Hello, Goodbye, Hello and goodbye]

>>> articles.get_list(complex=(Q(headline__startswith='Hello') & Q(headline__startswith='Goodbye')))
[]

>>> articles.get_list(complex=(Q(headline__startswith='Hello') & Q(headline__contains='bye')))
[Hello and goodbye]

>>> articles.get_list(headline__startswith='Hello', complex=Q(headline__contains='bye'))
[Hello and goodbye]

>>> articles.get_list(complex=(Q(headline__contains='Hello') | Q(headline__contains='bye')))
[Hello, Goodbye, Hello and goodbye]

>>> articles.get_list(complex=(Q(headline__iexact='Hello') | Q(headline__contains='ood')))
[Hello, Goodbye, Hello and goodbye]

>>> articles.get_list(complex=(Q(pk=1) | Q(pk=2)))
[Hello, Goodbye]

>>> articles.get_list(complex=(Q(pk=1) | Q(pk=2) | Q(pk=3)))
[Hello, Goodbye, Hello and goodbye]