Django filter not working when using F() with ManyToMany
I have the following query:
MyModel.objects.filter(foreing_key__value=F('value'))
And It works perfectly. But now I have some complex rules where I need to evaluate the ForeignKey value depending on some conditions. Just to simplify, if I refactor the query to:
MyModel.objects.annotate(
valid_value=F('foreing_key__value')
).filter(
valid_value=F('value')
)
It doesn't work when the foreing_key__value
is NULL
. Why is this happening? I think it's related to LEFT JOIN, which is not applied when using the F()
operator, but I'm unsure how to fix this issue.
Thanks in advance
For some reason, the filters with Q()
work when using the field name. But when F()
is applied, it evaluates to None
, and Q()
with equal conditions doesn't work as expected.
I have to fix it using the following code:
MyModel.objects.annotate(
valid_value=F('foreing_key__value')
).filter(
Q(valid_value__isnull=False) & Q(valid_value=F('value'))
)