spraj
spraj

Reputation: 65

Unable to append to list

    if sample_collected == 'true':
            b_id = list(Booking.objects.filter(center__isnull=False,org_type='homedx').values_list('id', flat=True))
            for booki_id in b_id:
                print("Booking ID", booki_id)
                if booki_id in list(ReceivedPackageTubes.objects.values_list('booking_id', flat=True)):

                    packages = list(Booking.objects.filter(id=booki_id).values_list('packages__name', flat=True))
                    print("Packages", packages)
                    count_tube = []
                    for i in packages:
                        pt = package_models.PackageTubes.objects.filter(package__name=i).values_list('tubequantity__tube__name', flat=True).count()
                        count_tube.append(pt)

                    total_tubes = sum(count_tube)
                    print("Total Tubes", total_tubes)

                    collected = list(ReceivedPackageTubes.objects.filter(booking_id=booki_id).values_list('booking_id', flat=True))
                    print("Collected", collected)
                    collected_ids = []
                    
                    if len(collected) == total_tubes:
                        collected_ids.append(booki_id)
                    print("Collected ID", collected_ids)

In the last line if len(collected) == total_tubes. I am trying to append **collected_id**. in collected_ids = []. Every time it is appending one. I know I need to use for loop but I am unable to do that. Can somebody help. I am learning Python and Django. Thank you !!

Upvotes: 0

Views: 81

Answers (1)

Jeremy
Jeremy

Reputation: 671

You're using a for loop to iterate over booki_id elements in b_id, and adding them to the collected_ids list. However, each time you process the next booki_id, you're resetting collected_ids to an empty list. Try moving the line:
collected_ids = []
outside the for loop, so that you only initialize the list once and avoid overwriting it.

Upvotes: 1

Related Questions