[Answered ]-Django and model`s property

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.

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
👤defuz

Leave a comment