Django中的ForeignKey是必需的吗?

1 投票
3 回答
541 浏览
提问于 2025-04-16 08:15

我有三个类:

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)

我这样做没有出错……看起来不错……

1

听起来你的数据库和模型不同步了。你可以选择删除并重新创建数据库,使用 manage.py syncdb 这个命令(这样做最简单,但会丢失数据,除非你使用像 fixtures 这样的工具来重新加载初始数据),或者使用像 South 这样的迁移工具,把现有的数据库升级,以符合新的数据模型。

撰写回答