我在使用Python 2.7.13(x86)的Django 1.6中有一个例外,我不知道要解决这个问题。我已经在其他帖子中搜索了答案,但无济于事。 我被困在这上面,并且已经旋转了一段时间。
这是抛出异常的代码行:
myNewClass.class_students = selectedClass.class_students.all()
请参阅下面的完整代码示例...
这是我收到的错误消息:
Cannot set values on a ManyToManyField which specifies an intermediary model. Use MyApp.ClassStudents's Manager instead.
(对于上述错误消息,我的应用程序被称为' MyApp' ...)
似乎所有()都不起作用,无论如何要解决这个问题? 你能帮助我解决这个问题,或者至少指出我正确的方向......
感谢。
这是我的代码:
class Class(models.Model):
courseNumber = models.IntegerField()
courseName = models.CharField(max_length = 32)
class_students = models.ManyToManyField(Student, blank = True, through = 'ClassStudent')
class Student(models.Model):
studentName = models.CharField(max_length = 32)
overallStudentGPA = models.IntegerField()
class ClassStudent(models.Model):
myClass = models.ForeignKey(Class, on_delete = models.CASCADE)
myStudent = models.ForeignKey(Student, on_delete = models.CASCADE)
studentClassGrade = models.IntegerField()
def copy_class(modeladmin, request, queryset):
for selectedClass in queryset:
myNewClass = Class(courseNumber = selectedClass.courseNumber, courseName = selectedClass.courseName)
myNewClass.courseNumber = selectedClass.courseNumber
myNewClass.courseName = selectedClass.courseName
# Throws an error:
# Cannot set values on a ManyToManyField which specifies an intermediary model. Use MyApp.ClassStudents's Manager instead.
myNewClass.class_students = selectedClass.class_students.all()
答案 0 :(得分:0)
以下是我提出的答案:
def copy_class(modeladmin, request, queryset):
myNewClass = Class(courseNumber = selectedClass.courseNumber, courseName = selectedClass.courseName)
myNewClass.courseNumber = selectedClass.courseNumber
myNewClass.courseName = selectedClass.courseName
myNewClass.save()
for studentObj in selectedClass.class_students.all():
oneClassStudentObj = ClassStudents.get(class = selectedClass, student = studentObj)
tempStudentClassGrade = oneClassStudentObj.studentClassGrade
tempClassStudent = ClassStudent(myClass = myNewClass, myStudent = studentObj, studentClassGrade = tempStudentClassGrade )
tempClassStudent.save()
我只是想知道是否有办法直接获取ClassStudent对象而不必使用ClassStudents.get(...)?它虽然有效......