2👍
Since you are defining a property on Article
, the actual database hit depends on how Article
querysets are retrieved. If you use select_related([depth=2])
on your queryset while retrieving the Article
objects, that would be the most optimal in terms of database hits irrespective of how you write the property. Both the ways you have listed have similar performance.
0👍
You should just call
article.book.author
This call will query book object and cache it on article instance. So if you call article.book.id after that first call it will not run the second query.
Personaly I think that you should try to avoid hitting the database in model methods as much as possible. Because, as your application gets complicated, developers will just call the author method of your article even if they also have book model in their hand. because two property is virtually same.
- [Answered ]-Totals/Subtotals in Django template
- [Answered ]-Django frontend and backend seperation for security
- [Answered ]-Django REST Framework: Purpose of CreateOnlyDefault
0👍
I prefer this option because it makes only one query to the database:
@property
def author(self):
authors = Author.objects.filter(book__article=self.id)[:1]
return authors[0] if authors else None
- [Answered ]-How to deal with a large queryset in Django
- [Answered ]-Get shipping address for a basket in django oscar
- [Answered ]-Change order ModelChoiceField
- [Answered ]-Why does push fail when upgrading to Cedar-14
- [Answered ]-How to specify authentication info to memcache with django?