导入表数据的Django ForeignKey

时间:2014-01-06 15:35:33

标签: django import foreign-keys

我有两个表,School和Scores,它们共有一个'psid'列。我将每个表中的数据导入我的应用程序。我想通过ForeignKey将两个表链接在一起(一个学校可以有多个分数)。

目前我的models.py看起来像这样:

class School(models.Model):
    psid = models.CharField(primary_key=True, max_length=5)
    city = models.CharField(max_length=100)

class Score(models.Model):
    psid = models.ForeignKey(School, max_length=5, db_column='psid')
    scores = models.IntegerField(max_length=2)

我是否需要在Scores中添加一个额外字段,以便我可以从原始表中导入psid列并且有一个ForeignKey字段通过'psid'列链接Scores和School?

感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

django模型在大多数情况下处理幕后连接表。 ForeignKey字段类型足以实现此目的,然后您只需使用ORM来连接查询中的表。以下是我根据您对所寻找内容的最佳解释来设置表格的方法:

from django.db import models


class School(models.Model):
    psid = models.CharField(primary_key=True, max_length=5)
    city = models.CharField(max_length=100)

    def __unicode__(self):
        return u"{0} ({1})".format(self.psid, self.city)


class Score(models.Model):
    school = models.ForeignKey(School, null=False, db_column="psid")
    score = models.IntegerField()

    def __unicode__(sefl):
        return u"Score({0}, {1})".format(self.school.psid, self.score)

然后测试你的模型:

$ ./manage.py syncdb
$ ./manage.py shell
>>> from schools.models import School, Score
>>> school1 = School(psid="S1", city="Springfield")
>>> school1
S1 (Springfield)
>>> school1.save()
>>> School.objects.get(psid="S1")
S1 (Springfield)
>>> school2 = School(psid="S2", city="Springfield")
>>> school2.save()
>>> score1 = Score(school=school1, score=3)
>>> score1
Score(S1, 3)
>>> score1.school.psid
S1
>>> score2 = Score(school=school1, score=2)
>>> score3 = Score(school=school2, score=5)
>>> score1.save()
>>> score2.save()
>>> score3.save()
>>> school1.score_set.all()
[Score(S1, 3), Score(S1, 2)]
>>> school2.score_set.all()
[Score(S2, 5)]
>>> Score.objects.all()
[Score(S1, 3), Score(S1, 2), Score(S2, 5)] 
>>> Score.objects.filter(school__psid="S1")
[Score(S1, 3), Score(S1, 2)]

我希望能帮到你。