0

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

2
  • Is valid_value itself NULL? It might be more useful to give some (sample) models and explain what you aim to achieve. Commented Nov 12, 2024 at 20:24
  • @willeM_VanOnsem Thanks for your time, I've fixed it checking by null values if F() operator is applied Commented Nov 12, 2024 at 21:00

2 Answers 2

1

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'))
)
Sign up to request clarification or add additional context in comments.

Comments

0

Fields in foreign keys or many-to-many models can be filtered without annotating them.

# MyModel.objects.filter(m2m_or_foreignkey__field=123)
MyModel.objects.filter(foreign_key__value=123)

1 Comment

Yep, but I have a complex Case/When so I need to make annotations. The example was just a simplified version of the problem

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.