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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With