Home > Blockchain >  Django queryset .iterate(): not working. Only first item is taken into account, second is ignored
Django queryset .iterate(): not working. Only first item is taken into account, second is ignored

Time:02-04

I have the following code. I know the queryset contains 2 items. However, Django only creates one entry. What am I overlooking?

I know "OrderItem.objects.filter(order=order)" returns two objects. However, in the order_lines.iterate() it only creates one entry. Do I overlook something?

            order_lines = OrderItem.objects.filter(order=order)
            inv_ref = (str(order.order_date.year)   "-"   str(10000 order.id))
            inv = Invoice.objects.create(invoice_ref=inv_ref,date=order.order_date, order=order, ship_to=order.order_ship_to, bill_to=order.order_bill_to)
            
            value = 0
            vat = 0
            total = 0
            commission = 0


            ## Looping not working properly: fix all items to be added to invoice.
            for item in order_lines.iterator():
                exvat = (item.price/((100 item.vat)/100))
                val = item.quantity * exvat
                ttl = (item.price*item.quantity)
                comm = item.commission
                vat_val = ttl-val
                
                InvoiceItems.objects.create(invoice=inv, order_item=item, quantity=item.quantity, price=exvat, value=val, vat=item.vat,vat_val=vat_val,total=ttl)
                value = value   val
                vat = vat   vat_val
                total = total   ttl
                commission = commission   comm
                print(item)

CodePudding user response:

Do not use .iterator() as django.models.Model.objects.filter() already returns an QuerySet which implements iterator protocol (Iterable[]).

...
for item in order_lines:
    ...
...

CodePudding user response:

Try simplified loop:

for item in order_lines:

it should work like a charm because it's already QuerySet object.

  •  Tags:  
  • Related