Skip to content Skip to sidebar Skip to footer

Save List Of Records And Fields Into Django Model

I receive this list from my website admin: [['present', '2'],['present', '1'], ['study', '1'], ['study', '3'], ['present', '4'], ['study', '4'], The first option is actually the

Solution 1:

Try something like this:

l=[['present', '2'], ['present', '3'], ['present', '4'], ['study', '2']]
dic={}
for arr in l:
    dic.setdefault(arr[1], []).append(arr[0])
for key in dic:
    Rollcall.objects.create(present=Trueif'present'in dic[key] elseFalse,\
    student=Trueif'student'in dic[key] elseFalse, \
    study=User.objects.get(id=int(key)))

or to make it in bulk after creating the dictionary (dic):

final_objects = [Rollcall(is_present=Trueif'present'in final_dic[key] elseFalse,
                          is_study=Trueif'study'in final_dic[key] elseFalse,
                          student=User.objects.get(id=int(key)),
                          ) for key in final_dic]
Rollcall.objects.bulk_create(final_objects)

Solution 2:

You can iterate over list, create Rollcall instances and use bulk_create()Manager/QuerySet method (This avoids a lot of database hits (Only one INSERT query will be enough) and gives you guarantee of atomicity).

data_list = [['present', '2'], ['present', '3'], ['present', '4'], ['study', '1']]

Rollcall.objects.bulk_create([
    Rollcall(present=Trueif present == 'present'elseFalse, student_id=int(student_id)) for present, student_id in data_list)
])

Hope, it helps you.

Post a Comment for "Save List Of Records And Fields Into Django Model"