问题
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 field name that needs to be edit in Rollcall model and the second option is the user ID.
Now I want to save this list to the Rollcall
model:
#models.py
class Rollcall(models.Model):
student = models.ForeignKey(User)
present = models.BooleanField(default=False)
study = models.BooleanField(default=False)
So I first check and find the various fields that a particular user has in the list, and then I will save all those fields for one user in my model. How can I do this?
--Update 1:
this is HTML
file:
{% forstudent in students %}
<tr>
<td>{{student}} </td>
<td> <input type="radio" name="present_{{student.id}}" value="1"></td>
<td> <input type="radio" name="study_{{student.id}}" value="1"></td>
</tr>
{% endfor %}
I get the data in this way and put them into the list that I explain in the first of this question:
data_list = [key.split('_') for key in request.POST.keys()][1:]
Each student can be present or absent or can study or not.my exactly question is: How can save data of all my student?Is there another way to solve this problem without data_list
or any other way to create better data_list
?
回答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=True if 'present' in dic[key] else False,\
student=True if 'student' in dic[key] else False, \
study=User.objects.get(id=int(key)))
or to make it in bulk after creating the dictionary (dic
):
final_objects = [Rollcall(is_present=True if 'present' in final_dic[key] else False,
is_study=True if 'study' in final_dic[key] else False,
student=User.objects.get(id=int(key)),
) for key in final_dic]
Rollcall.objects.bulk_create(final_objects)
回答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=True if present == 'present' else False, student_id=int(student_id)) for present, student_id in data_list)
])
Hope, it helps you.
来源:https://stackoverflow.com/questions/56310072/save-list-of-records-and-fields-into-django-model