使用外键django将数据导入sqlite数据库 [英] import data into sqlite database with foreign key django
问题描述
我想用一个外键(即班级信息)将学生的姓名列表导入数据库.
I want to import student's name list to database with one foreign key which is the class infomation.
Namelist Model.py:
Namelist Model.py:
name = models.CharField(max_length=100)
program = models.CharField(max_length=10)
classGrp = models.ForeignKey('GroupInfo', on_delete=models.SET_NULL, null=True)
名称列表中的数据如下:
the data in the namelist is like this:
id name program classGrp
1 ABHISHEK SINGH CE1 1
GroupInfo Model.py:
GroupInfo Model.py:
class GroupInfo(models.Model):
classGrp = models.CharField(max_length=10)
day = models.CharField(max_length=15)
groupInfo中的数据如下:
The data in the groupInfo is like this:
id classGrp day
1 FEP1 Tues
2 FSP1 Wed
当我导入名称列表数据时,例如:
When i import the namelist data, eg as below:
id name program classGrp
137 Dummy FP 2
它不存储2,即classGrp.当我在 http://127.0.0.1:8000/admin 上检查classGrp的详细信息时:classGrp在下拉列表中,显示classgr(FEP1,FSP1)而不是ID(1,2).
It does not store 2, which is the classGrp. When i check the detail of the classGrp at http://127.0.0.1:8000/admin: The classGrp is in dropdownlist displaying the classgr ( FEP1,FSP1) instead of the ID (1,2).
VIEW.PY:
def import_studName(request):
template = "import_stud.html"
prompt = {
'order' : 'Kindly ensure that the order of CSV should be id, name, program, classGrp'
}
if request.method == "GET":
return render(request, template, prompt)
csv_file = request.FILES['file']
if not csv_file.name.endswith('.csv'):
messages.error(request, 'This is not a csv file')
data_set = csv_file.read().decode('UTF-8')
io_string = io.StringIO(data_set)
next(io_string)
for column in csv.reader(io_string, delimiter=',', quotechar="|"):
if column[3] != '':
classGrp = GroupInfo.objects.get(pk = (column[3]))
else:
classGrp = GroupInfo.objects.get()
_, created = Namelist.objects.update_or_create(
id=column[0],
name=column[1],
program=column[2],
classGrp = column[3]
)
context = {}
return render(request,template, context)
这就是为什么它不导入为2的classGrp数据的原因.
And that is the reason why it does not import the classGrp data which is 2.
如何将外键ID导入数据库?
How do i import a foreign key id to the database?
错误消息:
无法分配'2'":"Namelist.classGrp"必须是"GroupInfo"实例.
Cannot assign "'2'": "Namelist.classGrp" must be a "GroupInfo" instance.
推荐答案
设法解决了我自己的问题.我的错误是我没有在namelist.update_or_create中调用classgrp.
Managed to solve my own question. My mistake was that i didnt call classgrp in the namelist.update_or_create.
这是更新的答案:
for column in csv.reader(io_string, delimiter=',', quotechar="|"):
if column[3] != '':
classGrp = GroupInfo.objects.get(pk = (column[3]))
else:
classGrp = GroupInfo.objects.get()
_, created = Namelist.objects.update_or_create(
id=column[0],
name=column[1],
program=column[2],
classGrp = GroupInfo.objects.get(pk = (column[3]))
)
这篇关于使用外键django将数据导入sqlite数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!