向Django数据库中的多个关系添加数据

2024-06-16 10:42:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用django 2.2、python 3.6.8和mysql服务器上的Ubuntu18.04。 我有课程表,学生表和课程表。 课程与学生之间存在着多对多的关系。 课程模式:

student = models.ManyToManyField(Student, blank=True, verbose_name=_("Öğrenci"))

我在模板中手动创建了一个表单,并手动插入数据。 视图.py:

studentnamesuuidlist = request.POST.getlist('ogrenci_isimleri') #list

student1 = Student.objects.filter(uuid=studentnamesuuidlist[0])
coursesobject.student.set(student1)
student2 = Student.objects.filter(uuid=studentnamesuuidlist[1])
coursesobject.student.set(student2) 

这门课有两个学生。学生uuid来自模板表单post。 当我运行以上行时,在courses\u student joint表中创建student2记录。 但是student1不是被创建的。它应该同时创建两个记录,但在联合表中只创建一个记录


Tags: 模板表单objectsuuid记录手动filterstudent
2条回答

您应该使用.add而不是.set参见this
.set重写和.add追加

studentnamesuuidlist = request.POST.getlist('ogrenci_isimleri') #list

student1 = Student.objects.filter(uuid=studentnamesuuidlist[0])
coursesobject.student.add(student1)
student2 = Student.objects.filter(uuid=studentnamesuuidlist[1])
coursesobject.student.add(student2) 

解决了

    studentnamesuuidlist = request.POST.getlist('ogrenci_isimleri') #list

    student1 = Student.objects.get(uuid=studentnamesuuidlist[0])
    student2 = Student.objects.get(uuid=studentnamesuuidlist[1])
    coursesobject.student.add(student1,student2) 
    coursesobject.save()        

相关问题 更多 >