将数据添加到Django数据库中的多对多关系

我在ubuntu 18.04和mysql服务器上使用django 2.2,python 3.6.8。 我有课程,学生表和课程表。 课程与学生之间存在多对多关系。 在课程模型中:

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

我在模板中手动创建了一个表单,并手动进行了数据插入。 Views.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) 

本课程有2名学生。学生uuid来自模板表单发布。 当我在行上方运行时,将在courses_student联合表中创建student2记录。 但是不创建student1。它应该创建两条记录,但是在联合表中仅创建一条记录。

beautytai 回答:将数据添加到Django数据库中的多对多关系

您应该使用.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) 
,

已解决。

   .ant-table th {
      line-height: 1;
      text-align: right;
      padding: 15px 9px;
      overflow-wrap: normal;
      white-space: nowrap;
    }
本文链接:https://www.f2er.com/3098533.html

大家都在问