Hi, I am trying to understand how to use the Django ORM. It seems like it is sometimes possible to access the same data through a forward relationship and a reverse relationship.
Context
Given these models:
class Author(models.Model):
name = models.CharField(max_length=255)
class Book(models.Model):
title = models.CharField(max_length=255)
author = models.ForeignKey(Author, on_delete=models.CASCADE)
price = models.DecimalField(max_digits=6, decimal_places=2)
class Order(models.Model):
book = models.ForeignKey(Book, on_delete=models.CASCADE)
quantity = models.IntegerField()
customer = models.ForeignKey(Customer, on_delete=models.CASCADE)
Let's say you want to find the total number of books written per author. It seems to me that this can be done two ways:
- Forward relationship from Book-->Author
Something like: Book.objects.values('author').annotate(book_count=Count('id')).order_by('author')
- Reverse relationship from Author-->Book
Author.objects.annotate((book_count=Count('book'))
Question
Assuming that both are valid, does it matter which one is used? Is one more efficient than the other? Thanks!