0

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 ?

David Robinson
  • 77,383
  • 16
  • 167
  • 187
flexxxit
  • 2,440
  • 5
  • 42
  • 69

2 Answers2

1

I think what you want is the related_name property of the ForeignKey field. This creates a link back to the Subject object and provides a manager you can use to query the set.

So to use this functionality, change the foreignkey line to:

subject=models.ForeignKey(Subject, related_name='questions')

Then with an instance of Subject we'll call subj, you can:

subj.questions.filter(year=2000)

I don't think this performs much differently to the technique you have used. Roughly speaking, SQL performance boils down a) whether there's an index and b) how many queries you're issuing. So you need to think about both. One way to find out what SQL your model usage is generating is to use SqlLogMiddleware - and alternatively play with the options in How to show the SQL Django is running It can be tempting when you get going to start issuing queries across relationships - e.g. q = Question.objects.get(year=2000, subject__name=SUBJ_MATHS) but unless you keep a close eye on these types of queries, you can and will kill your app's performance, badly.

Community
  • 1
  • 1
0

Django's query syntax allows you to 'reach into' related objects.

past_questions = Pastquestion.objects.filter(year=2000, subject__name=subject_name)
markdsievers
  • 7,151
  • 11
  • 51
  • 83
  • @Æsahættr answer is also a good one. If the context of your problem requires you to have the Subject object anyway, that would be a more efficient method. – markdsievers Nov 11 '12 at 17:16