The exception "Cannot resolve keyword 'origin_iso_code' into field" arises because the CurrencyExchange model does not have fields named origin_iso_code or target_iso_code. Instead, it has foreign key fields named origin and target which relate to the Currency model.
The CurrencyRepository.get_currency_exchanges method attempts to filter the CurrencyExchange model using origin_iso_code and target_iso_code, which are not direct fields on that model.
To fix this, you should filter using origin__iso_code and target__iso_code. This syntax is used in Django ORM to access fields of related models through foreign keys.
Here's the corrected code snippet from currency_repository.py:
python
from datetime import datetime
from typing import Optional
from profits.models import CurrencyExchange
from profits.services.exceptions import CurrencyExchangeNotFoundException
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)
if target_currency_code:
exchanges = exchanges.filter(target__iso_code=target_currency_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:
The original code had exchanges.filter(origin_iso_code=origin_currency_code) which tries to find a field origin_iso_code directly in CurrencyExchange model.
The CurrencyExchange model has origin which is a ForeignKey to Currency model and Currency model has iso_code field.
To access the iso_code field of the related Currency model through origin foreign key, we use origin__iso_code syntax.
Same logic applies for target field using target__iso_code.