gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 21:50:30 26 4
gpt4 key购买 nike

假设我有一个表 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com