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

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

问题描述

我正在和一些同事进行辩论。有没有一个首选的方法来检索一个Django中的对象,只有一个?



两个明显的方法是:

  try:
obj = MyModel.objects.get(id = 1)
除了MyModel.DoesNotExist:
#我们没有对象!做某事
通过

  objs = MyModel.objects.filter(id = 1)
如果len(objs)== 1:
obj = objs [0]
其他:
#我们没有对象!做某事
pass

第一种方法似乎在行为上更正确,但在控制流中使用异常这可能会引起一些开销。第二个是更迂回的,但永远不会提出例外。



有哪些想法是可取的?哪个更有效率?

解决方案

get()是为这种情况提供的。使用它。



选项2几乎正是如何在Django中实现 get()方法,所以在应该没有表现的差异(而且您正在考虑的事实表明您违反了编程的基本规则之一,即在编写和分析之前尝试优化代码 - 直到您有代码并且可以运行它,你不知道它将如何执行,然后尝试优化之前是痛苦的路径)。


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?

The two obvious ways are:

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

and

   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() is provided specifically for this case. Use it.

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天全站免登陆