Django,过滤最近添加的元素
我想检索最近添加的元素,如果根本没有,则分配一些默认值,例如:
query = X.objects.filter(name="aa",type="b")[0]
if query:
resultname =query.name
resulttype = query.type
else:
resultname = "a default name"
resulttype = "a default type"
这不起作用,因为当第一行 query = X.objects.filter( name="aa",type="b")[0]
,执行,过滤后的查询列表为空。
I want to retrieve the most recently added element and if there is none at all, assign some default values such as:
query = X.objects.filter(name="aa",type="b")[0]
if query:
resultname =query.name
resulttype = query.type
else:
resultname = "a default name"
resulttype = "a default type"
This is not working as it will raise an exception when the first line, query = X.objects.filter(name="aa",type="b")[0]
, executes and the filtered query list is empty.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对
QuerySet
建立索引会生成单个模型(如果存在)。如果不存在则捕获异常,或者预先在QuerySet
上使用len()
来查看是否找到任何记录。Indexing a
QuerySet
results in a single model, if any exist. Either catch the exception if none exist, or uselen()
beforehand on theQuerySet
to see if any records were found.