[Answered ]-How to use prefetch_related in django rest api with foreying key and heritage

1πŸ‘

βœ…

To prefetch setor_fii, you will have to go through asset. Since Fii inherits from Asset, Asset will have an automatically created one-to-one field named fii. You can then use that to access setor_fii:

PortfolioAsset.objects.filter(
    portfolio_id=self.kwargs['pk'],
).prefetch_related(
    'asset__fii__setor_fii',
)

Also since the whole relationships here are just one to ones, you can use select_related instead of prefetch_related to get them all in one query (compared to three queries using prefetch_related):

PortfolioAsset.objects.filter(
    portfolio_id=self.kwargs['pk'],
).select_related(
    'asset__fii__setor_fii',
)
πŸ‘€Brian Destura

Leave a comment