Skip to content

Transforming SQL Query to Django Expression

Assuming I have the following Django models and the according SQL-Tables with some data. I have simplified the models so that it is clearer.


class UserAnswer(models.Model):
  partquestion = models.ForeignKey(PartQuestion)
  answer = models.CharField()
id answer partquestion_id
1 667 1


class PartQuestion(models.Model):
  question = models.ForeignKey(Question)
  part = models.ForeignKey(Part)
id question_id part_id
1 1 1


class SingleInputSolution(models.Model):
    question = models.ForeignKey(Question)
    content = models.CharField()
id content question_id
1 667 1
2 85 2

I want to get all User answers where the answer is equal to the solution of the according question. I’ve came up with this SQL-Query but can’t really think of how to implement this into a Djano query:

select * from (useranswer join partquestion on 
useranswer.partquestion_id = join solution on 
partquestion.question_id = solution.question_id where answer=content;

This will output the following: useranswer.answer useranswer.partquestion_id partquestion.question_id partquestion.part_id solution.content solution.question_id
1 667 1 1 1 1 1 667 1

I just can’t get my head around this concept in Django. Maybe using F-Expressions and some stuff.

Thanks for any advice.



Okay well I just figured it out myself after reading the answer and comments from @Swift.



It’s pretty simple now after I got it but I just tried using solution_set instead of just solution.

5 People found this is helpful