Getting data from other table in model property


I have a model that has a dynamic property like:

class UserFund(models.Model):
    # field definitions here

    def user_currency_value(self):
        user_currency = self.user.currency
        fund_currency =
        return * * <currency conversion here>

The information about conversion rates is stored in another table Currency.

How to do this calculation without making a lot of extra queries?

Is it OK to query the whole Currency table once and use that as a lookup table inside this user_currency_value function? Will this be cached somehow? Is there a better way to do this?


This (old) SO question is about the same problem I have:

The main control technique here is with prefetch_related or select_related on Currency, wherever you query UserFund:

You detect when you need such a call with this library:

If you’re feeling adventurous you can try this library, which I’m developing with my ex-boss: . It changes the N+1 behaviour down to 2 queries instead, by automatically using prefetch_related on access. We hope to get it into Django core.


For my understanding (I’m new to Django), in the answer here:, would you apply prefetch_related in the MyModelManager?

Adding a prefetch_related() there would work. It could end up with overfetching though, as it will always prefetch, even on code paths that don’t touch your property.

1 Like