Search code examples
djangoforeign-keysnullable

Django filter a ForeignKey field when it is null


Let's say I have two tables in Django, TableA and TableB. Table A contains some boolean field, bool, and TableB contains a foreign key field, for_field to TableA, which can be Null.

class TableA(models.Model):
    bool = models.BooleanField()

class TableB(models.Model):
    for_field = models.ForeignKey('TableA', null=True)

If I want to filter TableB so as to get all the entries where for_field.bool is True or for_field is Null, what is the shortest way to achieve this?

I'm using .filter((Q(for_field__is_null=True) | Q(for_field__bool=True)), but I wonder if there's shorter code for this.


Solution

  • After some experiments it seems that .exclude(for_field__bool=False) will contain also for_field__isnull=True entries and will not raise any exceptions. You can be sure by executing .exclude(for_field__bool=False).filter(for_field__isnull=True) and see some results also.

    And honestly I don't know which option is faster, but IMO your variant with two Q objects much more readable because it shows logic you're really want. So I actually suggest you to stick with it.