Python Django 存在()与DoesNotExist

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40910149/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 00:11:13  来源:igfitidea点击:

Django exists() versus DoesNotExist

pythondjangoweb

提问by Dato Gachechiladze

I have some questions about django exists()and DoesNotExistexception.

我有一些关于 djangoexists()DoesNotExist异常的问题。

Example code:

示例代码:

id = 1
# first
if User.objects.get(pk=id).exists():
    # my logic
    pass
# second
try:
    User.objects.get(pk=id)
    # my logic
    pass
except User.DoesNotExist:
    return 0

I often use get()method. Which practice is better? Which code is better? The first or second?

我经常使用get()方法。哪种做法更好?哪个代码更好?第一个还是第二个?

回答by bignose

if User.objects.get(pk=id).exists()

if User.objects.get(pk=id).exists()

This won't work, so the question is pretty easy to answer: This way is inferior to the ways which do work :-)

这行不通,所以这个问题很容易回答:这种方式不如工作方式:-)

I guess you actually didn't make a Minimal Complete Verifiable Exampleand so missed the error when you posted un-verified code.

我猜您实际上没有制作最小完整可验证示例,因此在您发布未经验证的代码时错过了错误。



So instead, I suppose you are asking about the difference between:

所以相反,我想你是在问以下之间的区别:

  • QuerySet.exists()when you have a QuerySet (e.g. from a filter operation).

    For example:

  if User.objects.filter(pk=id).exists():
      # ... do the things that need that user to exist
  try:
      user = User.objects.get(pk=id)
  except User.DoesNotExist:
      # ... handle the case of that user not existing

The difference is:

区别在于:

  • The QuerySet.existsmethod is on a queryset, meaning you ask it about a query (“are there anyinstances matching this query?”), and you're not yet attempting to retrieve any specific instance.

  • The DoesNotExistexception for a model is raised when you actually attemptedto retrieve one instance, and it didn't exist.

  • QuerySet.exists方法位于查询集上,这意味着您向它询问查询(“是否有任何实例匹配此查询?”),并且您还没有尝试检索任何特定实例。

  • DoesNotExist当您实际尝试检索一个实例并且它不存在时,会引发模型的异常。

Use whichever one correctly expresses your intention.

使用正确表达您意图的任何一种。

回答by Andrii Soldatenko

You can find more info in docs: about exists(),but exists()works only for QuerySet

您可以在文档中找到更多信息: about exists(),但exists()仅适用于 QuerySet

Returns True if the QuerySet contains any results, and False if not. This tries to perform the query in the simplest and fastest way possible, but it does execute nearly the same query as a normal QuerySet query.

exists() is useful for searches relating to both object membership in a QuerySet and to the existence of any objects in a QuerySet, particularly in the context of a large QuerySet.

如果 QuerySet 包含任何结果,则返回 True,否则返回 False。这会尝试以最简单和最快的方式执行查询,但它执行的查询与普通 QuerySet 查询几乎相同。

exists() 对于与 QuerySet 中的对象成员资格和 QuerySet 中任何对象的存在相关的搜索非常有用,特别是在大型 QuerySet 的上下文中。

But ObjectDoesNotExistworks only with get().

ObjectDoesNotExist仅适用于get().

Also you can try another approach:

您也可以尝试另一种方法:

user = User.objects.filter(id=2)
if user:
    # put your logic
    pass

回答by Mohideen bin Mohammed

in django model, if you gonna use model.objects.get()if it wasn't exist it raise an error. in that case you can use DoesNotExistalong with except:

在 Django 模型中,如果您要使用model.objects.get()它,如果它不存在,则会引发错误。在这种情况下,您可以DoesNotExistexcept:

try:
  val = Model.objects.get(pk=val) # if nothing found it will raise an exception
exception:
  you can trace an exception without mentioning anything on top.
(or)
exception ObjectDoesNotExist:
  # it will come here if exception is DoesNotExist

回答by Raymond Mlambo

For Django version 2.0.6, you can do the following, and it will work:

对于 Django 2.0.6 版,您可以执行以下操作,它将起作用:

if Model.objects.filter(my_id=objectid).exists():
  myobject = get_object_or_404(Model, my_id=objectid)
  context = {'myobject': myobject}
  return render(request, self.template_name, context)

You can get more info here: https://docs.djangoproject.com/en/2.1/ref/models/querysets/

您可以在此处获取更多信息:https: //docs.djangoproject.com/en/2.1/ref/models/querysets/

回答by Yago Batista

It's my understanding that you're asking whether to use if statements or try catch on your code. I personally prefer to avoid using try catch, a think it's an ugly syntax, when I do want to raise an exception, I use a python keyword raise, to me, it makes the code cleaner.

我的理解是,您是在询问是使用 if 语句还是 try catch 代码。我个人更喜欢避免使用 try catch,认为这是一种丑陋的语法,当我确实想引发异常时,我使用 python 关键字 raise,对我来说,它使代码更清晰。

Code example:

代码示例:

user = User.objects.filter(id=2)
if not user:
   raise ObjectDoesNotExist

回答by Nick Cuevas

Since we are in Django, we'll try to catch the error with Django functionality instead of the common way(which is using Exceptions with Python).

由于我们在 Django 中,我们将尝试使用 Django 功能而不是常见方式(即在 Python 中使用异常)来捕获错误。

id = 1
def a_query(id):
  qs = User.objects.filter(pk=id)
  if qs.exists():
    return qs.first()
  return None

In here, the method exists() helps you catching the error(if there's any).

在这里,方法exists() 可以帮助您捕获错误(如果有的话)。

ref: https://docs.djangoproject.com/en/3.0/ref/models/querysets/#django.db.models.query.QuerySet.exists

参考:https: //docs.djangoproject.com/en/3.0/ref/models/querysets/#django.db.models.query.QuerySet.exists