需要 Django 外键吗?

发布于 2024-10-06 12:48:49 字数 434 浏览 0 评论 0 原文

我有三个课程:

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)

当我运行这个课程时,它抱怨学生没有考试的外键。为什么?

I have a three classes:

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)

When I run this it complains that Student doesn't have a a ForeignKey to Exam. Why?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

如日中天 2024-10-13 12:48:49

听起来您的实际数据库与您的模型不同步。您需要使用 manage.pysyncdb 删除并重新创建数据库(最简单,但除非您使用 重新加载初始数据的装置)或使用迁移工具,例如 South 升级现有数据库以反映新的数据模型。

It sounds like your actual database is out of sync with your model. You'll want to either drop and recreate your database using manage.py syncdb (easiest, but you will lose the data unless you use something like fixtures to reload initial data) or use a migration tool like South to upgrade your existing database to reflect the new data model.

和我恋爱吧 2024-10-13 12:48:49

你可以在manage.py shell上尝试这个:

from bar import models
l=models.Location("here")
s=models.Student(name="fred",email="[email protected]")
e = models.Exam(place=l,taker=s,score=99.9)

我可以毫无错误地做到这一点...对我来说看起来不错..

You can try this on the manage.py shell:

from bar import models
l=models.Location("here")
s=models.Student(name="fred",email="[email protected]")
e = models.Exam(place=l,taker=s,score=99.9)

which I can do with no errors... Looks good to me..

深陷 2024-10-13 12:48:49

admin.py 文件中,我有 inlines = [StudentsInline] 设置。这试图强制将多个学生添加到一项考试中(认为它位于 OneToMany 关系的一侧)。

In the admin.py file I had inlines = [StudentsInline] setting. This tries to enforce adding multiple Students to one exam (thinking it's on the One side of a OneToMany relationship).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文