views:

245

answers:

1

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

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, a custom manager method, or is there a way to generally override Django to return an empty set. For my purposes, DoesNot Exist isn't useful.

Alternately, the whole issue can be sidestepped with:

Blog.objects.select_related('post').get(author='John').post_set.values()
+9  A: 

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

Ben James
+1 this would be the standard practice, most easily recognized by another developer, and is semantically equivalent to the OP's goal.
David Berger
Something that wasn't clear from the original post is that this is all happening inside of a model method inside of Blog. Yours is probably the most parsimonious solution but I already have the Blog object instantiated, it would be great to use it.
Adam Nelson
The method suggested by Ben uses a class method on the Post class which is already instantiated. The fact that you already have a Blog instance is irrelevant since filterspecs are created from class models not the object instances.
Adam, in my experience when dealing with non-trivially complex queries the path of least resistance in Django will be to start with the Manager of the Model for which you want to get instances (in this case `Post.objects`).
Ben James