I have CurrencyHistory
model along with the database table which is populated on every Currency
model update for the historical data.
class CurrencyHistory(models.Model):
id = models.AutoField(primary_key=True)
change_rate_date = models.DateTimeField(_("Change Rate Date"),
auto_now=False, auto_now_add=True,
db_column='change_rate_date')
code = models.ForeignKey("core.Currency", verbose_name=_("Code"),
on_delete=models.CASCADE,
related_name='history',
db_column='code')
to_usd_rate = models.DecimalField(_("To USD Rate"),
max_digits=20,
decimal_places=6,
null=True,
db_column='to_usd_rate')
Database structure looks like
id | change_rate_date | code | to_usd_rate
1 | 2021-01-01 | EUR | 0.123456
2 | 2021-01-01 | CAD | 0.987654
3 | 2021-01-02 | EUR | 0.123459
4 | 2021-01-02 | CAD | 0.987651
I need to fetch data using Djnago ORM to have a dictionary to display single row per date with the every currency as columns, like this
Date | EUR | CAD |
---|---|---|
2021-01-01 | 0.123456 | 0.987654 |
2021-01-02 | 0.123459 | 0.987651 |
But I have no idea how to correctly do it using Django ORM to make it fast.
I suppose for loop over the all unique database dates to get dict for each data will work in this case but it looks very slow solution that will generate thousands of requests.