如何处理“匹配查询不存在”当得到一个对象 [英] How to handle "matching query does not exist" when getting an object

查看:92
本文介绍了如何处理“匹配查询不存在”当得到一个对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我想使用get()函数来选择对象,如

  personalProfile = World.objects.get(ID = personID)

如果get函数不返回找到一个值,则匹配查询不存在。 错误发生。



如果我不需要这个错误,我将使用try和except功能

  try:
personalProfile = World.objects.get(ID = personID)
除了:
pass
/ pre>

但是,我认为这不是最好的方式,因为我使用

 除了
通过

请推荐一些想法或代码示例来与这个问题

解决方案

这取决于你想做什么,如果它不存在..



Theres get_object_or_404


在给定的模型管理器上调用get(),但它会引发Http404而不是$ / $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ <<<<<<<<<<<<<<<<<<<<<<<<<<

哪个是非常接近的e尝试你当前所做的代码。



否则theres get_or_create

  personalProfile,created = World.objects.get_or_create(ID = personID)

虽然,如果你选择继续您目前的方法,至少要确保除了本地化正确的错误,然后根据需要执行某些操作。

 尝试:
personalProfile = World.objects.get(ID = personID)
除了MyModel.DoesNotExist:
raise Http404(No MyModel符合给定的查询)

上面的try / except句柄与get_object_or_404 ...的文档中找到的相似...


When I want to select objects with a get() function like

personalProfile = World.objects.get(ID=personID)

If get function doesn't return find a value, a "matching query does not exist." error occurs.

If I don't need this error, I'll use try and except function

try:
   personalProfile = World.objects.get(ID=personID)
except:
   pass

But I think this is not the best way since I use

except:
      pass

Please recommend some idea or code sample to fight with this issue

解决方案

That depends on what you want to do if it doesn't exist..

Theres get_object_or_404:

Calls get() on a given model manager, but it raises Http404 instead of the model’s DoesNotExist exception.

get_object_or_404(World, ID=personID)

Which is very close to the try except code you currently do.

Otherwise theres get_or_create:

personalProfile, created = World.objects.get_or_create(ID=personID)

Although, If you choose to continue with your current approach, at least make sure the except is localised to the correct error and then do something with that as necessary

try:
   personalProfile = World.objects.get(ID=personID)
except MyModel.DoesNotExist:
    raise Http404("No MyModel matches the given query.")

The above try/except handle is similar to what is found in the docs for get_object_or_404...

这篇关于如何处理“匹配查询不存在”当得到一个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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