class UserFund(models.Model):
# field definitions here
@property
def user_currency_value(self):
user_currency = self.user.currency
fund_currency = self.fund.currency
return self.fund.position * self.fund.price * <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?
If you’re feeling adventurous you can try this library, which I’m developing with my ex-boss: https://github.com/tolomea/django-auto-prefetch . 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.
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.