假设我有如下关系:
class Student(AbstractBaseUser):
# It inherits AbstractBaseUser and has it's own manger
# note: I did forget to add editable here
id = models.UUIDField(primary_key=True, default=uuid.uuid4)
firstname
lastname
...
class Teacher(models.Model):
id = models.UUIDField(default=uuid.uuid4, primary_key=True)
firstname
lastname
email
...
class Meeting(models.Model):
id = models.UUIDField(default=uuid.uuid4, primary_key=True, editable=False)
student = models.ManyToManyField(Student)
teacher = models.ManyToManyField(Teacher)
我应该如何为“学生”或“老师”字段添加/设置值。我试图将相关模型中的对象分配给它们,但出现错误:
禁止直接分配到多对多集合的前端。使用 student.set() 代替。
我也试过这个:
m = Meeting()
s = Student.objects.first() #to get a random student
m.student.add(s)
然后我得到: ValueError: Cannot add "<Student: sarah@gmail.com>": instance is on database "None", value is on database "default"
我也这样做了:
m = Meeting.objects.create() #It does only have two mentioned fields.
m.student.add(s)
我明白了: django.db.utils.ProgrammingError: column "meeting_id" is of type bigint but expression is of type uuid LINE 1: ..._meeting" ("meeting_id", "student_id") VALUES ('c7688df9-.. . ^ 提示:您将需要重写或强制转换表达式。