Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[FEEDBACK] Thoughts on foreign key fetching? #27

Open
kbyatnal opened this issue May 30, 2020 · 1 comment
Open

[FEEDBACK] Thoughts on foreign key fetching? #27

kbyatnal opened this issue May 30, 2020 · 1 comment

Comments

@kbyatnal
Copy link

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.

@phalt
Copy link
Owner

phalt commented Jun 1, 2020

Did you know you can build up query sets? They are lazily evaluated when you access some data. So you could optionally do the .select_related if a parameter is passed, for example. The API response will change shape though, so keeping an empty response in place would be a good idea, such as null values, or an empty object.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants