Добавление даты из внешнего API в ответ представления - Django
Я пытаюсь добавить некоторые данные из внешнего API в ответ представления. Мое представление уже отправляет данные из моей базы данных, и я хочу добавить некоторые данные из внешнего вызова API в представление.
Модели:
class Currency(models.Model):
"""Store information about a currency asset."""
id = models.IntegerField(primary_key=True)
user = models.ForeignKey(User, on_delete=models.CASCADE)
class Price(models.Model):
"""Store price about a currency asset."""
currency = models.ForeignKey(Currency, related_name="price", on_delete=models.CASCADE)
price = models.FloatField(blank=True, null=True)
View:
class CurrencyViewSet(viewsets.ModelViewSet):
serializer_class = serializers.CurrencySerializer
queryset = models.Currency.objects.all()
def get_queryset(self):
currencies = self.request.user.currencies_set.all()
ids = [currency.id for currency in currencies]
price = fetch_currency_price(ids) # fetch from external api
for currency in currencies:
currency.price.set(Price(currency_id=currency.id, price=price.get('id'))
return currencies
Который не работает. У меня куча разных ошибок, и я не могу разобраться.
В вашем случае одна валюта может иметь несколько цен (от одной до многих), поэтому будет более уместно, если вы сделаете цикл по ценам. Надеюсь, это даст вам то, что вам нужно!
class CurrencyViewSet(viewsets.ModelViewSet):
serializer_class = serializers.CurrencySerializer
queryset = models.Currency.objects.all()
def get_queryset(self):
currencies = self.request.user.currencies_set.all()
ids = [currency.id for currency in currencies]
prices_from_api = fetch_currency_price(ids) # fetch from external api
for currency in currencies:
prices_list_of_currency = currency.price.all()
for price_object in prices_list_of_currency:
price_object.price = VALUE_FROM_EXT_API # get appropriate value from prices_from_api external data.
price_object.save()
return currencies