Insert multiple list in database using python django

Question:

Im confused on how can I insert multiple list bycolumn using a loop, let say the output what I want in database is something like this

name         percentage       is_fixed_amount

PWD           20                   0
Senior        20                   0
OPD            6                   0
Corporators   20                   0
Special                            1

What I’ve tried but it’s insert multiple data and it didn’t reflect the actual data in database, Can somebody knows the solution? I appreciate any reply.

discount = ['PWD','Senior Citizen','OPD','Corporators','Special']
discount_percentage = ['20','20','6','20','']
fixed_amount = [False,False,False,False,True] 


for dis in discount:
    for per in discount_percentage:
        for fix in fixed_amount:
            discount_val = Discounts(name=dis,percentage = per,is_fixed_amount =fix)
            discount_val.save()
Asked By: marivic valdehueza

||

Answers:

You’re using nested loops to insert values into the database which iterates through the combination of each item 3 lists discount, discount_percentage, fixed_amount. You should try iterating using 1 for loop and access each item in the list by its index

discount = ['PWD','Senior Citizen','OPD','Corporators','Special']
discount_percentage = ['20','20','6','20','']
fixed_amount = [False,False,False,False,True] 


for i in range(len(discount)):
    discount_val = Discounts(name=discount[i],percentage = discount_percentage[i],is_fixed_amount =fixed_amount[i])
    discount_val.save()

Answered By: tax evader
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.