Django 过滤器与获取单个对象? [英] Django filter versus get for single object?

查看:22
本文介绍了Django 过滤器与获取单个对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我和一些同事就这个问题进行了辩论.当您只期待一个对象时,是否有一种首选方法可以在 Django 中检索一个对象?

I was having a debate on this with some colleagues. Is there a preferred way to retrieve an object in Django when you're expecting only one?

两种明显的方式是:

try:
    obj = MyModel.objects.get(id=1)
except MyModel.DoesNotExist:
    # We have no object! Do something...
    pass

还有:

objs = MyModel.objects.filter(id=1)

if len(objs) == 1:
    obj = objs[0]
else:
    # We have no object! Do something...
    pass

第一种方法在行为上似乎更正确,但在控制流中使用了可能会引入一些开销的异常.第二个更迂回,但永远不会引发异常.

The first method seems behaviorally more correct, but uses exceptions in control flow which may introduce some overhead. The second is more roundabout but won't ever raise an exception.

有什么想法更可取吗?哪个更有效率?

Any thoughts on which of these is preferable? Which is more efficient?

推荐答案

get() 提供 专门针对这种情况.使用它.

选项 2 几乎正是 get() 方法在 Django 中实际实现的方式,因此应该没有性能"差异(并且您正在考虑它的事实表明您'违反了编程的一项基本规则,即在代码被编写和分析之前尝试优化代码——直到你拥有代码并且可以运行它,你不知道它将如何执行,并在此之前尝试优化是一条痛苦之路).

Option 2 is almost precisely how the get() method is actually implemented in Django, so there should be no "performance" difference (and the fact that you're thinking about it indicates you're violating one of the cardinal rules of programming, namely trying to optimize code before it's even been written and profiled -- until you have the code and can run it, you don't know how it will perform, and trying to optimize before then is a path of pain).

这篇关于Django 过滤器与获取单个对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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