Every time a run my Django app, the same data is inserted into database. I only want to include data the first time, when there are no values in base(table). I am getting my data from API and Json.
view.py
from django.shortcuts import render, HttpResponse
from .models import Brands
import requests
def get_brends(request):
all_brands = {}
url ='http://makeup-api.herokuapp.com/api/v1/products.json?brand'
response = requests.get(url)
data = response.json()
for result in data:
brand_data = Brands(
name=result['name'],
price=result['price'],
image_link=result['image_link'],
brand=result['brand'],
category=result['category'],
product_type=result['product_type'],
description=result['description'],
)
brand_data.save()
all_brands=Brands.object.all().order_by('-id')
return render(request, 'brands_makeup/brands.html', { "all_brands":all_brands})
model.py
class Brands(models.Model):
name = models.CharField(max_length=100, default="None")
price = models.DecimalField(decimal_places=3,max_digits=4,null=True,blank=True)
image_link = models.CharField( max_length=50, blank = True, null = True)
brand = models.CharField( max_length=150, blank = True, null = True)
category = models.CharField( max_length=150, blank = True, null = True)
product_type = models.CharField( max_length=150, blank = True, null = True)
description = models.CharField( max_length=1500, blank = True, null = True)
def __str__(self):
return self.name , self.price , self.category , self.brand
I am only trying to include JSON once in my database when a database is empty.