使用 Django 在数据库中获取不需要的特定记录的最快方法
Fastest way to get a not required specific record in database using Django
使用 Django 获取可以存在或不存在的特定记录的最快方法是什么。
一些可能的方法:
results = ModelExample.objects.filter(label="example1")
if(results.exists())
item = results.first()
results = ModelExample.objects.filter(label="example1")
if(len(results) > 0)
item = results.first()
*** 编辑 ***
我对我原来的问题不清楚,我真正的搜索是一种从查询集中的可为空对象 return 获取 属性 的方法,如果该对象存在,请取 属性 如果没有 return None.
我在 JavaScript.
上寻找类似于 item?.value 的东西
幸运的是@Willem 帮助我在已接受的答案上显示 getattr(...) 函数。
您可以使用 .first()
。如果该项目不存在,它将return None
,所以:
result = ModelExample.objects.filter(label='example1')<b>.first()</b>
if result is None:
# does not exists
# …
pass
您可以使用单线获得 属性 与:
result = getattr(
ModelExample.objects.filter(label='example1').first(),
'<i>name-of-the-attribute</i>',
None
)
item = ModelExample.objects.filter(label="example1").first()
.first() "Returns 查询集匹配的第一个对象,或者 None 如果没有匹配的对象。"
使用 Django 获取可以存在或不存在的特定记录的最快方法是什么。
一些可能的方法:
results = ModelExample.objects.filter(label="example1")
if(results.exists())
item = results.first()
results = ModelExample.objects.filter(label="example1")
if(len(results) > 0)
item = results.first()
*** 编辑 ***
我对我原来的问题不清楚,我真正的搜索是一种从查询集中的可为空对象 return 获取 属性 的方法,如果该对象存在,请取 属性 如果没有 return None.
我在 JavaScript.
上寻找类似于 item?.value 的东西幸运的是@Willem 帮助我在已接受的答案上显示 getattr(...) 函数。
您可以使用 .first()
。如果该项目不存在,它将return None
,所以:
result = ModelExample.objects.filter(label='example1')<b>.first()</b>
if result is None:
# does not exists
# …
pass
您可以使用单线获得 属性 与:
result = getattr(
ModelExample.objects.filter(label='example1').first(),
'<i>name-of-the-attribute</i>',
None
)
item = ModelExample.objects.filter(label="example1").first()
.first() "Returns 查询集匹配的第一个对象,或者 None 如果没有匹配的对象。"