Django中的ForeignKey是必需的吗?
我有三个类:
class Location(models.Model):
name = models.CharField(max_length = 200)
class Student(models.Model):
name = models.CharField(max_length = 200)
email = models.EmailField()
class Exam(models.Model):
place = models.ForeignKey(Location)
taker = models.ForeignKey(Student)
score = models.DecimalField(max_digits = 5, decimal_places = 2)
当我运行这个的时候,它提示说学生类没有指向考试类的外键。为什么会这样呢?
3 个回答
0
在 admin.py
文件里,我设置了 inlines = [StudentsInline]
。这个设置是想让一个考试可以添加多个学生(因为我认为这是“一对多”关系中的“一”这一方)。
1
你可以在 manage.py 的命令行界面试试这个:
from bar import models
l=models.Location("here")
s=models.Student(name="fred",email="foo@bar.com")
e = models.Exam(place=l,taker=s,score=99.9)
我这样做没有出错……看起来不错……