ivbtar
ivbtar

Reputation: 879

Adding data to many-to-many relation in Django database

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.

Upvotes: 0

Views: 97

Answers (2)

Faisal Manzer
Faisal Manzer

Reputation: 2129

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) 

Upvotes: 1

ivbtar
ivbtar

Reputation: 879

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

Upvotes: 0

Related Questions