[Django]-Django get objects not referenced by foreign key

35👍

Something like this:

AA.objects.filter(state=10, bb=None)

0👍

The question is old, but the answers and comments was really helpful until 9 years after.
Though, even after read the @Daniel Roseman’s great answer (thanks man, your answer helped me a lot), so I checked it out a little bit further at the documentation how it works.

You can read below as it is in the documentation:

Lookups that span relationships

Django offers a powerful and intuitive way to “follow” relationships in lookups, taking care of the
SQL JOINs for you automatically, behind the scenes. To span a
relationship, use the field name of related fields across models,
separated by double underscores, until you get to the field you want.

This example retrieves all Entry objects with a Blog whose name is
‘Beatles Blog’:

>>> Entry.objects.filter(blog__name='Beatles Blog') 

It works backwards, too. To refer to a “reverse” relationship, use the lowercase name of the model.

Using django polls tutorial as example, with Questions and Choices as follows:

# models.py
class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
# Select Questions without related Choices
>>> Question.objects.filter(choice=None)

# Select only Questions with related Choices
>>> Question.objects.exclude(choice=None)

# Select Questions related to Choice with id 1
>>> Question.objects.filter(choice__id=1)

Leave a comment