如何处理“匹配查询不存在"获取对象时 [英] How to handle "matching query does not exist" when getting an object

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

问题描述

当我想使用 get() 函数选择对象时

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

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

如果 get 函数没有返回 find 值,则匹配查询不存在".发生错误.

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

如果我不需要这个错误,我会使用 try 和 except 函数

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:

Theres get_object_or_404:

在给定的模型管理器上调用 get(),但它引发了 Http404 而不是模型的DoesNotExist 异常.

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)

除了您当前执行的代码之外,这与 try 非常接近.

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

否则有get_or_create:

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

不过,如果您选择继续当前的方法,至少要确保将 except 本地化为正确的错误,然后根据需要对其进行处理

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.")

上面的 try/except 句柄类似于在文档中找到的 get_object_or_404...

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

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