【问题标题】:Adding data to many-to-many relation in Django database将数据添加到 Django 数据库中的多对多关系
【发布时间】:2020-03-11 02:37:27
【问题描述】:

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

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) 

本课程有 2 名学生。学生 uuid 来自模板表单帖子。 当我在上面运行时,在 courses_student 联合表中创建了 student2 记录。 但是 student1 没有被创建。它应该创建两条记录,但它只在联合表中创建一条记录。

【问题讨论】:

    标签: python django django-models django-views django-mysql


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      解决了。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-06-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-10-13
        • 1970-01-01
        • 2019-02-09
        • 2017-07-09
        相关资源
        最近更新 更多