Django Models.py N对N的关系,总是说一个对象没有定义
Django Models.py N to N relationship, always says one object is not defined
我正在与学院、教师和学生一起使用 Django 项目进行简单测试。
我正在尝试这个:
class Student(models.Model):
name = models.CharField()
direction = models.CharField()
city = models.CharField()
telephone = models.CharField(max_length=9)
email = models.EmailField()
teachers = models.ForeignKey(Teacher)
class Teacher(models.Model):
name = models.CharField(max_length=50)
direction = models.CharField(max_length=150)
city = models.CharField(max_length=50)
telephone = models.CharField(max_length=9)
email = models.EmailField()
students = models.ForeignKey(Student)
class Academy(models.Model):
name = models.CharField(max_length=50)
direction = models.CharField(max_length=150)
city = models.CharField(max_length=50)
teacher = models.ForeignKey(Teacher, blank=True, null=True)
students = models.ForeignKey(Student)
问题是如果我实现第一个Student,没有找到老师来制作外键,如果我实现第一个Teacher,也是一样。
有什么方法可以在像 C 中的函数一样实现模型之前定义它们?
谢谢!
就在 Student
模型中将外键设置为 Teahcer
模型作为字符串:
teachers = models.ForeignKey('Teacher')
如前所述here:
If you need to create a relationship on a model that has not yet been
defined, you can use the name of the model, rather than the model
object itself
我正在与学院、教师和学生一起使用 Django 项目进行简单测试。
我正在尝试这个:
class Student(models.Model):
name = models.CharField()
direction = models.CharField()
city = models.CharField()
telephone = models.CharField(max_length=9)
email = models.EmailField()
teachers = models.ForeignKey(Teacher)
class Teacher(models.Model):
name = models.CharField(max_length=50)
direction = models.CharField(max_length=150)
city = models.CharField(max_length=50)
telephone = models.CharField(max_length=9)
email = models.EmailField()
students = models.ForeignKey(Student)
class Academy(models.Model):
name = models.CharField(max_length=50)
direction = models.CharField(max_length=150)
city = models.CharField(max_length=50)
teacher = models.ForeignKey(Teacher, blank=True, null=True)
students = models.ForeignKey(Student)
问题是如果我实现第一个Student,没有找到老师来制作外键,如果我实现第一个Teacher,也是一样。
有什么方法可以在像 C 中的函数一样实现模型之前定义它们?
谢谢!
就在 Student
模型中将外键设置为 Teahcer
模型作为字符串:
teachers = models.ForeignKey('Teacher')
如前所述here:
If you need to create a relationship on a model that has not yet been defined, you can use the name of the model, rather than the model object itself