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)])