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')
精彩评论