当我想使用 get() 函数选择对象时,例如
personalProfile = World.objects.get(ID=personID)
如果 get 函数未返回查找值,则“匹配的查询不存在”。发生错误。
如果我不需要这个错误,我将使用 try 和 except 函数
try:
personalProfile = World.objects.get(ID=personID)
except:
pass
但我认为这不是最好的方法,因为我使用
except:
pass
请推荐一些想法或代码示例来解决这个问题
这取决于你想做什么,如果它不存在的话..
Theres get_object_or_404 https://docs.djangoproject.com/en/1.8/topics/http/shortcuts/#get-object-or-404:
在给定的模型管理器上调用 get(),但它会引发 Http404,而不是模型的DoesNotExist 异常。
get_object_or_404(World, ID=personID)
这与您当前执行的 try except 代码非常接近。
否则有get_or_create https://docs.djangoproject.com/en/1.8/ref/models/querysets/#get-or-create:
personalProfile, created = World.objects.get_or_create(ID=personID)
不过,如果您选择继续当前的方法,至少要确保 except 本地化为正确的错误,然后根据需要执行某些操作
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...
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)