Django:从DB获取对象,如果没有匹配,则为“None” [英] Django: Get an object form the DB, or 'None' if nothing matches

查看:180
本文介绍了Django:从DB获取对象,如果没有匹配,则为“None”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



现在我正在使用如下代码:

有没有Django函数让我从数据库中获取一个对象, / p>

  foo = Foo.objects.filter(bar = baz)
foo = len(foo)> 0和foo.get()或None

但这不是很清楚,而且到处都是乱七八糟的

解决方案

在Django 1.6 中,您可以使用 first / code> Queryset方法。它返回由查询器匹配的第一个对象,如果没有匹配的对象,则返回None。



用法:

  p = Article.objects.order_by('title','pub_date')。first()


Is there any Django function which will let me get an object form the database, or None if nothing matches?

Right now I'm using something like:

foo = Foo.objects.filter(bar=baz)
foo = len(foo) > 0 and foo.get() or None

But that's not very clear, and it's messy to have everywhere.

解决方案

In Django 1.6 you can use the first() Queryset method. It returns the first object matched by the queryset, or None if there is no matching object.

Usage:

p = Article.objects.order_by('title', 'pub_date').first()

这篇关于Django:从DB获取对象,如果没有匹配,则为“None”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆