Description
Would love to get your thoughts on the best way to handle accessing nested foreign key relationships. Here's a made up example (where the relationship is Book
-> Author
-> PublishingCompany
).
Domain Inventory
:
# models.py
class Book(models.Model):
author = models.ForeignKey(Author)
class Author(models.Model):
publishing_company = models.ForeignKey(PublishingCompany)
class PublishingCompany(models.Model):
...
# apis.py
class BookAPI:
@staticmethod
def get(*, book_id: uuid.UUID) -> Dict:
return BookService.get_book(id=book_id)
Now let's say we have another Domain, Purchasing
that's responsible for placing orders. From this domain, say we want to do something access some info via book.author.publishing_company
. What would be the best way to handle this?
I can see two options, but neither seem great.
Option 1: Inside BookService.get_book()
, we can add Book.objects.get(id=id).select_related('author__publishing_company')
. The downside of this is that we are always fetching extra data, whether the caller uses it or not.
Option 2: Inside the Purchasing
domain, we issue separate calls to BookAPI
, PublishingCompanyAPI
, etc but this is also doing extra work.
Ideally, there would be some way of cleanly passing to BookAPI
which data should be fetched.