Home > Blockchain >  Insert data from an API on the database - Django project
Insert data from an API on the database - Django project

Time:10-14

I would like to save product data from an API in a table in my database that I created

Models.py

class Product(models.Model):
  code=models.CharField(max_length=70,primary_key=True)
  designation=models.TextField()

  def __str__(self):
    return self.product.code

views.py

from .models import Product

def products(request):
  url='http://myAPI/Product/GetProducts'
  x=requests.get(url)
  content=x.json()
  all_product=content['products']
  for product in all_product:
     product=Product()
     product.save()
  return render(request,'cart/product.html',context)

How to proceed to insert each product in the table with the for loop ?? Note that each product is characterized by a code and a designation

CodePudding user response:

You can do bulk_create:

def products(request):
  url='http://myAPI/Product/GetProducts'
  x=requests.get(url)
  content=x.json()
  all_product=content['products']
  
  create_obj = []
  for product in all_product:    
      create_obj.append(Product(code=product['code'],
                        designation=product['designation']))
  product_data = Product.objects.bulk_create(create_obj)
  return render(request,'cart/product.html',{"product_data":product_data} )

  • Related