Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 218
mathiascg Avatar asked Jul 28 '16 16:07

mathiascg


2 Answers

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.

like image 107
valignatev Avatar answered Oct 12 '22 15:10

valignatev


I'm pretty sure, that your option is the shortest possible (correct me if I'm wrong). That is because you can't do OR queries without Q objects.

like image 20
JustLive Avatar answered Oct 12 '22 14:10

JustLive