The error occurs because you're trying to filter the CurrencyExchange model using origin_iso_code in the CurrencyRepository.get_currency_exchanges() method, but this field doesn't exist in the CurrencyExchange model.
Looking at the CurrencyExchange model in profits/models.py, it has a ForeignKey relationship with the Currency model through the fields origin and target. This means you need to filter using the related fields of the Currency model, not directly on the CurrencyExchange model.
The Fix
Instead of filtering using origin_iso_code and target_iso_code, you need to filter using the related field origin__iso_code and target__iso_code. This is how Django ORM allows querying across ForeignKey relationships.
Here’s the corrected get_currency_exchanges method:
python
class CurrencyRepository:
@[Redacted Person]
def get_currency_exchanges(
origin_currency_code: Optional[str],
target_currency_code: Optional[str],
date_start: Optional[datetime],
date_end: Optional[datetime]) -> dict:
"""
Loads currency exchange rates from the database, filtered by the given parameters and in ascending order by date.
Returns a dictionary with the exchange rates, where the keys are the dates
and the values are dictionaries with the exchange rates for that date.
The keys of the inner dictionary are strings of the form
"origin-target", where origin and target are the ISO codes of the
currencies, and the values are the exchange rates.
"""
exchanges = CurrencyExchange.objects
if origin_currency_code:
exchanges = exchanges.filter(origin__iso_code=origin_currency_code) # Use origin__iso_code
if target_currency_code:
exchanges = exchanges.filter(target__iso_code=target_currency_code) # Use target__iso_code
if date_start:
exchanges = exchanges.filter(date__gte=date_start)
if date_end:
exchanges = exchanges.filter(date__lte=date_end)
exchanges = exchanges.order_by('date')
if not exchanges.exists():
raise CurrencyExchangeNotFoundException(
f"No exchange rates found for {origin_currency_code}-{target_currency_code} "
f"between {date_start} and {date_end}")
exchange_dict = {}
for exchange in exchanges:
exchange_dict[exchange.date] = exchange.rate
return exchange_dict
Explanation of the Fix
origin__iso_code and target__iso_code:
origin is a ForeignKey to the Currency model, so origin__iso_code refers to the iso_code field in the related Currency model.
Similarly, target__iso_code refers to the iso_code field in the related Currency model for the target ForeignKey.
Why the Error Occurred:
The original code tried to filter directly on origin_iso_code, which doesn't exist in the CurrencyExchange model.
The correct way to filter on fields of related models is to use the double-underscore (__) notation to traverse the ForeignKey relationship.
Testing the Fix
You can test the fix by calling the get_currency_exchanges method with valid parameters: