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.
0👍
Django’s query syntax allows you to ‘reach into‘ related objects.
past_questions = Pastquestion.objects.filter(year=2000, subject__name=subject_name)