Updating Database via GET request to Generic views in Django

I've got this Generic view that would list records from my DB for GET request to localhost:8000 However, I also want to UPDATE those records upon GET. For instance, GET localhost:8000 would return a list like so:

[
    {
        "user": 1,
        "address": "sdfgasgasdfg",
        "balance": "123.00000000"
    },
    {
        "user": 1,
        "address": "sdfgasgasdfg25",
        "balance": "123.00000000"
    }
]

Upon GET, I would like to also make an API to https://www.blockchain.com/api/blockchain_api to get the latest BTC balance and update the balance values for those addresses in my DB. Not quite sure how to do so with generic views

view

class WalletListCreateAPIView(generics.ListCreateAPIView):
    queryset = Wallet.objects.all()
    serializer_class = WalletSerializer

model

class Wallet(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    address = models.CharField(max_length=34)
    balance = models.DecimalField(max_digits=16, decimal_places=8)
    slug = models.SlugField(max_length=34, blank=True, null=True)

    def __str__(self):
        return self.address

    def save(self, *args, **kwargs):
        self.slug = slugify(self.address)
        super().save(*args, **kwargs)

I would override the list(...) method of the API (which is getting called on GET request)

class WalletListCreateAPIView(generics.ListCreateAPIView):
    queryset = Wallet.objects.all()
    serializer_class = WalletSerializer

    def pull_data_from_api_and_update_db(self):
        # do some stuff here
        pass

    def list(self, request, *args, **kwargs):
        self.pull_data_from_api_and_update_db()
        return super().list(request, *args, **kwargs)

Here, you can add/update the pull_data_from_api_and_update_db(...) method the way you wish to.

Back to Top