1

I was wondering what the correct way is to delete one table in the database and update it with new information from an external API every time that is called. Basically, whenever the API would be called, the information saved in the table should be substituted by new one.

my views.py

from rest_framework import generics
from .serializers import TickerSerializer
from ticker.models import Ticker
import requests
import logging
logger = logging.getLogger(__name__)

class TickerList(generics.ListAPIView):
    serializer_class = TickerSerializer
    queryset = Ticker.objects.all()
    
class TickerRetrieve(generics.RetrieveUpdateDestroyAPIView):
    serializer_class = TickerSerializer
    queryset = Ticker.objects.all()
    lookup_field = 'id'    
    
    def get_object(request):
        url = 'https://api.kraken.com/0/public/Ticker?pair=1INCHEUR,1INCHUSD'
        response = requests.get(url)
        data = response.json()
        for key in data['result']:
            if isinstance(data['result'][key], int):
                continue
            crypto_data =data['result'][key]
            ticker_data = Ticker(crypto = (key),
                                crypto = (key),
                                a_0 = (crypto_data.get('a')[0]),
                                )
            ticker_data.save()

my models.py

from django.db import models

class Ticker(models.Model):
    id = models.AutoField(primary_key=True)  # auto increment field
    crypto = models.CharField(blank=True, null=True, max_length=25)
    a_0 = models.FloatField(null=True, blank=True, default=None)

my serializers.py

from rest_framework import serializers
from ticker.models import Ticker

class TickerSerializer(serializers.ModelSerializer):
    class Meta:
        model = Ticker
        fields = (
            'id', 
            'crypto',
            'a_0',
        )

my urls.py

from .views import TickerList, TickerRetrieve
from django.urls import path

app_name = 'ticker'
urlpatterns = [
    path('', TickerList().as_view(), name='ticker'),
    path('tickerretrieve/', TickerRetrieve().as_view(), name='tickerretrieve'),
]

Every time that i invoke the API tickerretrieve/ it adds more info to the table, while i need to first delete the existing one. I researched and tried thoroughly many similar cases here, but none had the example of an an external API with RetrieveUpdateDestroy.

David
  • 97
  • 7

0 Answers0