对于Django模型,是否有查看记录是否存在的捷径?

2024-05-15 12:42:45 发布

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

假设我有一个表People,有没有办法快速检查名为'Fred'People对象是否存在?我知道我可以质疑

People.objects.filter(Name='Fred')

然后检查返回结果的长度,但是有没有更优雅的方法呢?


Tags: 对象方法nameobjectsfredfilterpeople办法
3条回答

从Django 1.2开始,您可以在QuerySet上使用.exists(),但在以前的版本中,您可能会享受到this ticket中描述的非常有效的技巧。

更新

正如最近的回答中提到的,自从Django 1.2以来,您可以使用exists()方法来代替(link)。


原始答案:

不要对结果使用len(),应该使用People.objects.filter(Name='Fred').count()。根据django的文件

count() performs a SELECT COUNT(*) behind the scenes, so you should always use count() rather than loading all of the record into Python objects and calling len() on the result (unless you need to load the objects into memory anyway, in which case len() will be faster).

来源:Django docs

QuerySet API中的exists()方法可用since Django 1.2

相关问题 更多 >