python - 对于 Django 模型,是否有查看记录是否存在的快捷方式?

标签 python django django-models

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

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

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

最佳答案

更新:

正如最近的回答中提到的,从 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

关于python - 对于 Django 模型,是否有查看记录是否存在的快捷方式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2854080/

相关文章:

python - 我是否应该始终在 `except` 语句中指定异常类型?

jquery - GSUTIL 签名 Url PUT 到 Google Cloud Storage 失败

python - Django 民意调查应用程序 : OperationalError: attempt to write a read only database

python - 为什么 matplotlib 不能在 pycharm 中绘制工作?

python - 具有完整行对象的 Mongo Distinct Query

javascript - 在 Django 中创建一个带有更新和删除按钮的表单

python - 图书对象不可迭代 : Trying to display similar objects of an instance based on a field

django - 无法在 __init__.py django 1.9.4 中导入模型

django - 根据其他字段在 Django 中的用户模型中自动创建用户名

python - 使用来自不同模块的 python 装饰器函数