如果一个对象存在于 django 视图中而不返回404,那么验证该对象的正确方法是什么?

我需要验证一个对象是否存在并返回该对象,然后根据该对象执行操作。什么是正确的方法做到这一点,而不返回一个404?

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


if listing:
94731 次浏览

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

You can also do:

if not RealEstateListing.objects.filter(slug_url=slug).exists():
# do stuff...

Sometimes it's more clear to use try: except: block and other times one-liner exists() makes the code looking clearer... all depends on your application logic.

listing = RealEstateListing.objects.filter(slug_url=slug).first()

I would do it as simple as follows:

listing = RealEstateListing.objects.filter(slug_url=slug)
if listing:
# do stuff

I don't see a need for try/catch. If there are potentially several objects in the result, then use first() as shown by user Henrik Heino