iNikkz iNikkz - 3 years ago 165
MySQL Question

Django JOIN on nested model Foreign key with look up field

I'm using 2 models in Django Rest Framework.

class Questions(models.Model):
question = models.TextField()
answer = models.TextField()
timestamp = models.DateTimeField(auto_now_add=True)
categories = models.ForeignKey(Categories, related_name="cat_questions", on_delete=models.CASCADE)


class QuestionnaireResult(models.Model):
patient_info = models.ForeignKey(PatientInfo, related_name="+", on_delete=models.CASCADE)
questions = models.ForeignKey(Questions, related_name="result_questions", on_delete=models.CASCADE)
answer_given = models.TextField()
timestamp = models.DateTimeField(auto_now_add=True)


having serializers for both:

class QuestionnaireResultSerailizer(serializers.ModelSerializer):
class Meta:
model = QuestionnaireResult
fields = '__all__'


class QuestionsSerializer(serializers.ModelSerializer):
result_questions = QuestionnaireResultSerailizer(many=True)

class Meta:
model = Questions
fields ='__all__'


Using URL -
http://localhost:9000/api/questions/1
, It gives result based on question_id = 1 and result_questions contains only those nested records which have questions id == 1. That is correct.

{
"id": 1,
"result_questions": [
{
"id": 1,
"answer_given": "no",
"timestamp": "2017-10-01T12:28:19.770454Z",
"patient_info": 1,
"questions": 1
},
{
"id": 4,
"answer_given": "no",
"timestamp": "2017-10-01T13:13:19.658930Z",
"patient_info": 2,
"questions": 1
}
],
"question": "digestive ques 1",
"answer": "yes",
"timestamp": "2017-09-30T17:04:59.143857Z",
"categories": 1
}


But above nested json (result_questions) returns all patient_info which has questions id == 1 but I want to add one more filter(patient_info) on it. I want only those patient_info which I want to retrieve by passing as look up field.

What I want is that. Assume, I use this url
http://localhost:9000/api/questions/1?patient_info=1


It returns response having question_id == 1 and patient_info ==1. Therefore, response should be like:

{
"id": 1,
"result_questions": [
{
"id": 1,
"answer_given": "no",
"timestamp": "2017-10-01T12:28:19.770454Z",
"patient_info": 1,
"questions": 1
}
],
"question": "digestive ques 1",
"answer": "yes",
"timestamp": "2017-09-30T17:04:59.143857Z",
"categories": 1
}

Answer Source

you can try serializermethodfield

class QuestionsSerializer(serializers.ModelSerializer):
    result_questions = serializers.SerializerMethodField()

    class Meta:
        model = Questions
        fields ='__all__'

    def get_result_questions(self, obj):
        qs = obj.result_questions.all()
        request = self.context.get('request')
        patient_info = request.GET.get('patient_info')
        if patient_info:
            qs = qs.filter(patient_info=patient_info)
        return QuestionnaireResultSerailizer(qs, many=True).data
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download