Skip to content
Advertisement

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.

UserAnswer:

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

PartQuestion:

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

Solution:

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 = partquestion.id) join solution on 
partquestion.question_id = solution.question_id where answer=content;

This will output the following:

useranswer.id useranswer.answer useranswer.partquestion_id partquestion.id partquestion.question_id partquestion.part_id solution.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.

Advertisement

Answer

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

It’s:

UserAnswer.objects.filter(partquestion__question__solution__content=F('answer'))

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

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement