Foreign Key Relationships

Posted by Yehonathan Quartey on Stack Overflow See other posts from Stack Overflow or by Yehonathan Quartey
Published on 2012-11-11T16:56:18Z Indexed on 2012/11/11 17:00 UTC
Read the original article Hit count: 121

I have two models

class Subject(models.Model):
    name = models.CharField(max_length=100,choices=COURSE_CHOICES)
    created = models.DateTimeField('created', auto_now_add=True)
    modified = models.DateTimeField('modified', auto_now=True)
    syllabus = models.FileField(upload_to='syllabus')
    def __unicode__(self):
        return self.name

and

class Pastquestion(models.Model):
    subject=models.ForeignKey(Subject)
    year =models.PositiveIntegerField()
    questions = models.FileField(upload_to='pastquestions')
    def __unicode__(self):
        return str(self.year)

Each Subject can have one or more past questions but a past question can have only one subject. I want to get a subject, and get its related past questions of a particular year. I was thinking of fetching a subject and getting its related past question.

Currently am implementing my code such that I rather get the past question whose subject and year correspond to any specified subject like

this_subject=Subject.objects.get(name=the_subject)
thepastQ=Pastquestion.objects.get(year=2000,subject=this_subject)

I was thinking there is a better way to do this. Or is this already a better way? Please Do tell ?

© Stack Overflow or respective owner

Related posts about django

Related posts about django-models