0

I've a queryset of items.

And I've used itertools grouper to group them by 3.

However, when the list contains more than a mutiple of 3, for example 7 elemenets, the last tuple is completed with None.

I need to go through all groups (that contain 3 elements) and for each element:
- Test if it is not None.
- Compare the prices of each element inside the group, and return the id of the element with the lowers price and it's price.

views.py:

Queryset:

 pack_items = PackItem.objects.filter(cart=cart)

Grouping by 3:

pack_items_grouped_by_3 = list(grouper(pack_items, 3))

    for p_item in pack_items_grouped_by_3:
        print(type(p_item)) #prints <class 'tuple'>
        print(p_item) #prints (<PackItem: PackItem object (65)>, <PackItem: PackItem object (66)>, <PackItem: PackItem object (67)>)
        for a, b, c in p_item:
            if a is not None:
                print(a)
                #print(a.pack.price)
            elif b is not None:
                print(b)
                #print(b.pack.price)
            elif c is not None:
                print(c)
                #print(c.pack.price) 

Error:

for a, b, c in p_item: TypeError: cannot unpack non-iterable PackItem object

Omar Gonzales
  • 3,806
  • 10
  • 56
  • 120

1 Answers1

0

What's happening is that when you run

for element in p_item:

element will be the three pack item instances in the tuple that is p_item. The error is raised because it's trying to split a single PackItem instance into a, b, c.

You could do either of the following:

a, b, c = p_item

Or what I think is better:

    pack_items_grouped_by_3 = list(grouper(pack_items, 3))

    for a, b, c in pack_items_grouped_by_3:
        if a is not None:
            print(a)
            #print(a.pack.price)
        elif b is not None:
            print(b)
            #print(b.pack.price)
        elif c is not None:
            print(c)
            #print(c.pack.price) 
schillingt
  • 13,493
  • 2
  • 32
  • 34