0
I am using Postman to insert some data(structure below) in the database via POST, but it is only saving the first item of the list, someone can help me, please?
Structure of the POST:
{
"products": [
{
"id": 1,
"quantity": 17
},
{
"id": 2,
"quantity": 2
}
]
}
py.models
from django.db import models
class Checkout(models.Model):
pedido = models.IntegerField(primary_key=True, verbose_name="ID")
total_amount = models.DecimalField(max_digits=50, decimal_places=2, default=0.00,
verbose_name='Valor total')
total_amount_with_discount = models.DecimalField(max_digits=50, decimal_places=2, default=0.00, verbose_name='Valor total com desconto')
total_discount = models.DecimalField(max_digits=50, decimal_places=2, default=0.00, verbose_name='Desconto total')
class Meta:
verbose_name = 'Pedidos'
verbose_name_plural = 'Pedidos'
def __str__(self):
return 'Pedido: {}'.format(self.pedido)
class CartItem(models.Model):
pedido_id = models.IntegerField()
product_id = models.IntegerField()
quantity = models.CharField(max_length=5, verbose_name='Quantidade', default=1, blank=True, null=True)
line_item_total = models.CharField(max_length=5, verbose_name='Total', blank=True, null=True)
class Meta:
verbose_name = 'Itens dos Checkout'
def __str__(self):
return '{} - {}'.format(self.product_id, self.quantity)
py views.
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
from apps.checkout.models import Checkout, CartItem
from apps.checkout.serializers import CartItemSerializer
class JSONResponse(HttpResponse):
def __init__(self, data, **kwargs):
content = JSONRenderer().render(data)
kwargs['content_type'] = 'application/json'
super(JSONResponse, self).__init__(content, **kwargs)
@csrf_exempt
def checkout(request):
if request.method == 'GET':
itens = CartItem.objects.all()
itensSerializer = CartItemSerializer(itens, many=True)
return JSONResponse(itensSerializer.data)
elif request.method == 'POST':
data = JSONParser().parse(request)
cartItem = CartItem()
for item in data['products']:
product_id = item['id']
product_quantity = item['quantity']
cartItem.pedido = checkout.pedido
cartItem.product_id = product_id
cartItem.quantity = product_quantity
unit_amount = 100
cartItem.line_item_total = unit_amount * product_quantity
cartItem.save()
itens = CartItem.objects.all()
serializer = CartItemSerializer(itens, many=True)
return JSONResponse(serializer.data)
py serializers.
from rest_framework import serializers
from .models import CartItem
class CartItemSerializer(serializers.ModelSerializer):
class Meta:
model = CartItem
fields = ['id', 'product_id', 'quantity']
Hi, you’re giving Return inside the for in views.py so it goes in, goes through the first record and already comes out. In my view this Return should be a tab on the left. Inside Elif.
– Valmor Flores