[Answer]-Django ForeignKey for Imported Table Data

1👍

django models handle linking the tables behind the scenes for the most part. The ForeignKey field type is enough to accomplish this, then you just have to use the ORM to join the tables in a query. Here is how I would set up your tables based on my best interpretation of what you are looking for:

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)

Then to test your models out:

$ ./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)]

I hope that helps you out.

Leave a comment