Wednesday 15 April 2015

Best Practice to get related values in django without DoesNotExist error -


If I have two models:

  class blog (models.model): author = Model Kharefild () Class Post (model.model): blog = model Forinki (blog)  

And I have to get all the posts for a given blog:

blog.objects.get (author = 'John'). Post_set

If the author has a blog with = 'John' but not posted, a DoNotExist exception is raised. What is the best solution? I can try one thing: Except: On the front-end, a custom manager method, or there is normally a way to override Django to return a blank set. For my purposes, DoesNot does not exist.

Alternatively, the entire issue can be pressed like this:

  blog.objects.select_related ('post'). (Author = 'John'). Post_set.values ​​()  

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


No comments:

Post a Comment