Querying on existence of a relationship

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
from django.db import backend, models


class Foo(models.Model):
    name = models.CharField(maxlength=250)


class Bar(models.Model):
    name = models.CharField(maxlength=250)
    foo = models.ForeignKey(Foo)


# Retrieve all Foo objects which have at least one                                                                                                                                                       
# Bar object referencing them:                                                                                                                                                                           
Foo.objects.extra(where=['id IN (SELECT %s FROM %s)' % (backend.quote_name('foo_id'), Bar._meta.db_table)])

# Retrieve all Foo objects which have zero Bar                                                                                                                                                           
# objects referencing them:                                                                                                                                                                              
Foo.objects.extra(where=['id NOT IN (SELECT %s FROM %s)' % (backend.quote_name('foo_id'), Bar._meta.db_table)])

More like this

  1. Manager introspecting attached model by ubernostrum 5 years, 2 months ago
  2. Cached lookup model mixin by isagalaev 5 years, 3 months ago
  3. Left Outer join Q object by karsu 5 years, 11 months ago
  4. Improved Pickled Object Field by taavi223 3 years, 9 months ago
  5. Allow filtering and ordering by counts of related query results by exogen 6 years, 1 month ago

Comments

(Forgotten your password?)