[Fixed]-Simplifying this django query – Have django obtain instances based on values

1👍

Try out this.

answer = modelInterviewAnswer.objects.get(patients__patient_name=patient_name, questions__question=quest)

Please go through this documentation to know how to write query that span relationship.

I want to draw you attention at naming convention.

  1. Don’t prefix model name with model, for example modelPatient should be only Patient.
  2. Don’t need to write patient_<field_name> in model. It should be only <field_name>

For example your Paitent model should look like

class Patient(models.Model):
    name = models.CharField(max_length=128, unique=False)
    sex = models.CharField(max_length=128, unique=False)
    image = models.ImageField(upload_to='images/')

Follow same instructions for other models too.

class InterviewQuestion(models.Model):
    question = models.CharField(max_length=1000, unique=True)

class InterviewAnswer(models.Model):
    patients = models.ForeignKey(modelPatient)
    interview_questions = models.ForeignKey(modelInterviewQuestion)
    patient_response = models.CharField(max_length=1000, unique=True)

So Your query will be.

answer = InterviewAnswer.objects.get(patients__name=patient_name, interview_questions__question=quest)

Leave a comment