exists 函数在 Django 的 ORM 中是否有性能成本?

Does the exists function have a performance cost in Django's ORM?

假设我正在尝试查询 table,如下所示:

if MyModel.objects.filter(field1='some-value', field2='some-value').exists():
    obj = MyModel.objects.select_related('related_model_1', 'related_model_2').get(field1='some-value', field2='some-value')
else:
    return Response({'detail': 'Not found'}, status=status.HTTP_404_NOT_FOUND)

我是否通过检查是否存在然后选择相关字段来产生性能成本?还是小到可以忽略不计?

是的,它会查询数据库,但是可能的最小查询。

docs所述:

Returns True if the QuerySet contains any results, and False if not. This tries to perform the query in the simplest and fastest way possible, but it does execute nearly the same query as a normal QuerySet query.

Additionally, if a 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.