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.

2 Answers 2

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) 
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.