Home > Software engineering >  'bytes' object has no attribute 'items' while using list
'bytes' object has no attribute 'items' while using list

Time:08-19

Getting error in: items = [item for item in body.items()]

I just want to add multiple orderitems.

I don't know this loop will work after this error.

But atleast you will understand my requirement

I am giving following data:

[
    {
        "service_id": 1,
        "quantity": 2,
        "price": 20
    },
    {
        "service_id": 2,
        "quantity": 3,
        "price": 20
    },
    {
        "service_id": 3,
        "quantity": 4,
        "price": 20
    }
]
@api_view(['GET', 'POST'])
@csrf_exempt
# class CreteOrderView(View):
def create_order(request, *args, **kwargs):

    if request.method == 'POST':
        
        now = datetime.date.today()
        order = Order.objects.create(date=now)
        order.save()
        orderid = order.id
        order_id = orderid
        data = json.loads(request.body)
        price = request.session.get('price')
        quantity = request.session.get('quantity')
        print('quantity '   str(quantity))
        service_id = request.session.get('service_id')
        body = request.body
        items = [item for item in body.items()]
        for item in items:
            orderitemcreate= OrderItem.objects.create(order_id_id=order_id,
                                                    service_id_id=service_id,
                                                    quantity=quantity,
                                                    price=price)
            orderitemcreate.save()
        return Response({"Order_id":str(order.id),
                        "Order_date":str(order.date),
                        "OrderItems_id" :str(orderitemcreate.id),
                        "service_id" :str(orderitemcreate.service_id),
                        "quantity" :str(orderitemcreate.quantity),
                        "price":str(orderitemcreate.price)})
        
    else:
        order_qs = models.Order.objects.all().values_list()
        OrderItem_qs = models.OrderItem.objects.all().values_list()
        return Response({"Order":str(order_qs),"OrderItem":str(OrderItem_qs)})

CodePudding user response:

You already have

 data = json.loads(request.body)

so I think you should use:

items = [item for item in data.items()]
  • Related