Home > Mobile >  Transforming SQL Query to Django Expression
Transforming SQL Query to Django Expression

Time:12-17

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.

CodePudding user response:

You can just use values and the __ relations to traverse the foreign keys.

UserAnswer.objects.values('id', 'answer', 'partquestion_id', 'partquestion_set__id', 'partquestion_set__question_id')

Unfortunately it isn't obvious enough to me how to get those columns for the last table, but I hope that from this answer you can see how to do it?

CodePudding user response:

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.

CodePudding user response:

If you define your models like this:

class UserAnswer(models.Model):
   question = models.ForeignKey(questions,on_delete=models.CASCADE)
   user_answer = models.CharField()

class questions(models.Model):
   question = models.CharField()
   answer = models.CharField()

then this filter must work

right_answers = UserAnswer.objects.filter(question__answer = user_answer )
  • Related