0

I am using django 2.2, python 3.6.8 on ubuntu 18.04 with mysql server. I have courses, student and courses_student tables. There is a many-to-many relation between courses and students. In Courses model :

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

I manually created a form in a template and making data insertions manually. 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) 

There are 2 students for this course. Student uuid's are coming from template form post. When i run above lines, student2 record is created in courses_student joint table. But student1 is not created. It should create both records but it is creating only one record in joint table.

ivbtar
  • 799
  • 11
  • 29

2 Answers2

1

You should use .add instead of .set see this.
.set rewrites and .add appends.

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) 
Faisal Manzer
  • 2,089
  • 3
  • 14
  • 34
0

Solved.

    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()        
ivbtar
  • 799
  • 11
  • 29