最佳实践,在Django中获取相关值而不会出现DidNotExist错误 [英] Best Practice to get related values in django without DoesNotExist error

查看:62
本文介绍了最佳实践,在Django中获取相关值而不会出现DidNotExist错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在Django中有两个模型:

If I have two models in Django:

class Blog(models.Model):
    author = models.CharField()

class Post(models.Model):
    blog = models.ForeignKey(Blog)

我想获取给定博客的所有帖子:

And I want to get all posts for a given blog:

Blog.objects.get(author='John').post_set

如果博客的 author ='John'但不包含帖子中,引发 DoesNotExist 异常。最好的解决方案是什么?

If there is a Blog with author='John' but not posts, a DoesNotExist exception is raised. What is the best solution to this?

我可以在前端进行 try .. c或自定义管理器方法。有没有一种方法通常可以覆盖Django以返回空集?对我来说, DoesNotExist 没什么用。

I can do a try..except on the front-end, or a custom manager method. Is there a way to generally override Django to return an empty set? For my purposes, DoesNotExist isn't useful.

或者,整个问题可以回避:

Alternately, the whole issue can be sidestepped with:

Blog.objects.select_related('post').get(author='John').post_set.values()


推荐答案

您也可以通过使用 Post.objects.filter(blog__author = '约翰')

这篇关于最佳实践,在Django中获取相关值而不会出现DidNotExist错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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