Averin Maxim Averin Maxim - 3 years ago 149
Python Question

Speeding up django .exists()

I have a query

. I need to check if object is exist or not and if so, return object (or several objects). I have read that
is more fastest way to do it, but I should make 2 requests.

if TranslationStep.objects.filter(step_id=pk).exists():
return TranslationStep.objects.filter(step_id=pk)
return None

How can I optimise it?

Answer Source

You shouldn't do this at all. filter() will return an empty queryset if there is no match, which is False in a boolean context.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download