0

I have this json data

{
    'items_data': [
        {'item': 'Datalogger', 'hsn': '123', 'unit_name': 'BAG', 'unit_price': '100', 'quantity': '4',
         'tax_code': 'GST 18', 'base_discount': '4', 'discount_value': 16, 'amount': 384, 'state': 'Maharashtra',
         'invoice_number': 'TES-0822-97', 'tax_no': '18', 'tax_name': 'GST', 'base_Amount': 400, 'CGST': 36, 'SGST': 36}, 

        {'item': 'Datalogger', 'hsn': '123', 'unit_name': 'BAG', 'unit_price': '100', 'quantity': '4', 
         'tax_code': 'GST 28', 'base_discount': '4', 'discount_value': 16, 'amount': 384, 'state': 'Maharashtra',
         'invoice_number': 'TES-0822-97', 'tax_no': '28', 'tax_name': 'GST', 'base_Amount': 400, 'CGST': 56, 'SGST': 56}],

 'invoice_num': 'TES-0822-97',

 'gst_data': [
    {'tax_no': '18', 'totalGST': 72, 'total_base_amount': 400, 'cgst': 36, 'sgst': 36},
    {'tax_no': '28', 'totalGST': 112, 'total_base_amount': 400, 'cgst': 56, 'sgst': 56}
  ]
}

Now I want to get items data and store into database by query set. how can I save this by using query set objects?

I am doing this code

def get_invoice_items(request):

json_body = json.loads(request.body)
print(json_body)
for data in json_body["items_data"]:
    print(data)
    items=Items_Details.objects.bulk_create(data)
    print(items)

return JsonResponse({"message" : "Request Handled.."})

but getting error

1 Answers1

0

bulk_create requires objects' list as the first argument. Try the following

    items = []
    for data in json_body["items_data"]:
        # create item objects through django rest framework deserialization.
        # or 
        items.append(Item_Details(**data))
    Item_Details.objects.bulk_create(items)

PS: This would only work if all the fields in data dict are fields in the model. Can a dictionary be passed to django models on create?