开发者

Django ForeignKey Required?

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?


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.


You can try this on the manage.py shell:

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)

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


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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜