David
David

Reputation: 97

How to solve "'int' object is not subscriptable" in Django from a Kraken API

I was wondering what the correct way is to save a number in Django SQLite coming from a Kraken API, when there is an Array of Array of strings or integers (https://docs.kraken.com/rest/#operation/getOHLCData).

my views.py

from rest_framework import generics
from .serializers import KrakenSerializer
from krakenohlc.models import Krak
import requests

class KrakenList(generics.RetrieveAPIView):
    serializer_class = KrakenSerializer
    queryset = Krak.objects.all()

    def get_object(request):
        url = 'https://api.kraken.com/0/public/OHLC?pair=XBTEUR'
        response = requests.get(url)
        data = response.json()

        for i in data['result'].values():  
            kraken_data = Krak(
                time_0=(i[0][0]),
            )
            kraken_data.save()

my models.py

from django.db import models
class Krak(models.Model):
    time_0 = models.IntegerField(blank=True, null=True)

    def __str__(self):
        return self.time_0

This is the error that i get in the browser: enter image description here

The SQLite response is actually saving the API number in the database: enter image description here

I researched and tried thoroughly many similar cases here, but none had the example of an API response with this error message.

Upvotes: 1

Views: 195

Answers (1)

vinkomlacic
vinkomlacic

Reputation: 1879

I think the issue is the with the last item in the "result" array of arrays - "last". It seems like it's just a number. I guess you need some type checking in the algorithm. enter image description here

Suggestion for code modification:

for i in data['result'].values():
  # Skips "last" attribute
  if isinstance(i, int):
    continue
  kraken_data = Krak(
    time_0=(i[0][0]),
  )
  kraken_data.save()

Upvotes: 1

Related Questions