简体   繁体   English

加快Django .exists()

[英]Speeding up django .exists()

I have a query TranslationStep.objects.filter(step_id=pk) . 我有一个查询TranslationStep.objects.filter(step_id=pk) I need to check if object is exist or not and if so, return object (or several objects). 我需要检查对象是否存在,如果存在,请返回对象(或几个对象)。 I have read that .exists() is more fastest way to do it, but I should make 2 requests. 我读过.exists()是最快的方法,但是我应该发出2个请求。

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

How can I optimise it? 我该如何优化?

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. 如果不存在匹配,filter filter()将返回一个空的查询集,在布尔上下文中为False。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM