Database From An External API in Django

I am new to django
I am trying to make an claorie tracker app in which, i want to fetch data from this api “https://api.api-ninjas.com/v1/nutrition?query=” but on checking my model it shows 0 objects.Iam not able to do it correctly, can someone tell me where is the issue and me solve it

`

def index(request):
    if 'name' in request.GET:
        name = request.GET['name']
        url = "https://api.api-ninjas.com/v1/nutrition?query=" + name
        headers = {'X-Api-Key': 'api key'}
        response = requests.get(url, headers=headers)
        
        if response.status_code == 200:
            data = response.json().get('data', [])
            
            for item in data:
                FoodItem.objects.get_or_create(
                    name=item['name'],
                    calories=item['calories'],
                    carbohydrates=item['carbohydrates_total_g'],
                    protein=item['protein_g'],
                    fat=item['fat_total_g'],
                    fibre=item['fiber_g']
                )        
                print('saved')
        else:
            print(f"Error: {response.status_code}")
    return render(request, 'food.html')


from django.db import models
from django.contrib.auth.models import User

# Create your models here.
class FoodItem(models.Model):
    name = models.CharField(max_length=255)
    calories = models.PositiveIntegerField()
    carbohydrates = models.FloatField()
    protein = models.FloatField()
    fibre = models.FloatField()
    fat = models.FloatField()
    date = models.DateField()

    def __str__(self):
        return self.food_item


class UserFoodConsumption(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    food_item = models.ForeignKey(FoodItem, on_delete=models.CASCADE)
    date = models.DateTimeField(auto_now_add=True)

    

I want to store all information from api to my model “FoodItem”

  • did you verify / print the response from api to see if you are getting the correct response? If so can you post a snipped of the API response in your question?

    – 

Leave a Comment