开发者

Best Practice to get related values in django without DoesNotExist error

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 b开发者_JAVA百科log:

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

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

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()


You can also avoid the error by using Post.objects.filter(blog__author='John')

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜