I was wondering what the simplest way is to return null in Django when there is an empty list coming from an API "leverage_buy": [],:
my views.py
from django.shortcuts import render
from meal_app.models import Kraken
import requests
def get_krakens(request):
all_krakens = {}
url ='https://api.kraken.com/0/public/AssetPairs'
response = requests.get(url)
data = response.json()
for i in data['result'].values():
kraken_data = Kraken(
altname = i['altname'],
leverage_buy = i['leverage_buy'][0],
)
kraken_data.save()
my models.py
from django.db import models
class Kraken(models.Model):
altname = models.CharField(max_length=50, blank = True, null = True)
leverage_buy = models.IntegerField(blank=True, null=True)
Postman response
{
"error": [],
"result": {
"1INCHEUR": {
"altname": "1INCHEUR",
"leverage_buy": [],
I researched and tried thoroughly many similar cases here, but none had the example of an API empty list.
CodePudding user response:
You can work with a ternary operator:
for i in data['result'].values():
kraken_data = Kraken.objects.create(
altname = i['altname'],
leverage_buy = i['leverage_buy'][0] if i['leverage_buy'] else None
)