惯用/快速Django ORM检查mysql/postgres上是否存在

2024-03-29 02:13:58 发布

您现在位置:Python中文网/ 问答频道 /正文

如果我想检查对象是否存在,如果可能的话,检索一个对象,下面哪种方法更快?更地道?为什么?如果不是我列出的两个例子中的任何一个,还有一个是怎么做的呢?你知道吗

if Object.objects.get(**kwargs).exists():
    my_object = Object.objects.get(**kwargs)


my_object = Object.objects.filter(**kwargs)
if my_object:
    my_object = my_object[0]

如果相关的话,我关心mysql和postgres。你知道吗


Tags: 对象方法getifobjectsobjectmyexists
2条回答

django提供了^{}的一个非常好的概述

使用第一个示例,它将根据documentation执行两次查询:

if some_queryset has not yet been evaluated, but you know that it will be at some point, then using some_queryset.exists() will do more overall work (one query for the existence check plus an extra one to later retrieve the results) than simply using bool(some_queryset), which retrieves the results and then checks if any were returned.

因此,如果你打算使用这个对象,在检查是否存在之后,文档建议你只使用它,并强制使用一次评估

if my_object:
  pass

为什么不在try/except块中执行此操作以避免多个查询/查询,然后是if?你知道吗

try:
    obj = Object.objects.get(**kwargs)
except Object.DoesNotExist:
    pass

只需在except下添加else逻辑。你知道吗

相关问题 更多 >