如果一个对象存在于django视图中而不返回404,那么正确的方法是什么? [英] what is the right way to validate if an object exists in a django view without returning 404?

查看:179
本文介绍了如果一个对象存在于django视图中而不返回404,那么正确的方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上只是验证一个对象是否存在并返回该对象。然后根据执行动作。我想知道什么是正确的方法,而不返回404?

basically just verify if an object exists and return the object. then based on that perform actions. I'm wondering whats the right way to do it without returning a 404?

try:
    listing = RealEstateListing.objects.get(slug_url = slug)
except:
    listing = None

if listing:


推荐答案

如果没有给出404,我不会使用404包装器。这是滥用意图。只需抓住DoesNotExist。

I would not use the 404 wrapper if you aren't given a 404. That is misuse of intent. Just catch the DoesNotExist, instead.

try:
    listing = RealEstateListing.objects.get(slug_url=slug)
except RealEstateListing.DoesNotExist:
    listing = None

这篇关于如果一个对象存在于django视图中而不返回404,那么正确的方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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