将记录和字段列表保存到Django模型中 [英] Save list of records and fields into django model

查看:106
本文介绍了将记录和字段列表保存到Django模型中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从我的网站管理员那里收到此列表:

I receive this list from my website admin:

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

第一个选项实际上是需要在Rollcall模型中进行编辑的字段名称,第二个选项是用户ID.

The first option is actually the field name that needs to be edit in Rollcall model and the second option is the user ID.

现在,我想将此列表保存为Rollcall模型:

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?

-更新1: 这是HTML文件:

{% 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:]

每个学生都可以在场或不在场或者不能学习.我的确切问题是:如何保存我所有学生的数据?是否有另一种方法可以解决此问题而无需data_list或任何其他方法来解决?创建更好的data_list?

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?

推荐答案

尝试如下操作:

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)))

或在创建字典(dic)后批量制作:

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)

这篇关于将记录和字段列表保存到Django模型中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆