James Franco
James Franco

Reputation: 4706

Django : One model has two foreign keys is this the right approach in this case

I am currently learning about Django Models. Here is my current situation. I have three models

1-Patient_Names
2-Patient_Responses
3-Doctor_Questions

Now here is the relationship there will be multiple patients which will be represented by the model Patient_Names. Now each patient will have specific responses to the questions asked by a doctor these responses are represented by the model Patient_Responses. Because of this the Patient_Responses model will have a field that is a foreignKey to the Patient_Names model.Also since the responses will be for the questions from the model Doctor_Questionsthe Patient_Response has another field that is foreignKey to the model Doctor_Questions. Is this the right approach ? Can a model have two foreign keys?

Patient_Names                 Doctor_Questions
   |                                  |
   |---------Patient_Responses -------|       
                 |
                 pname = models.ForeignKey(Patient_Names)
                 doctor_questions = models.ForeignKey(Doctor_Questions)  

Upvotes: 2

Views: 85

Answers (1)

e4c5
e4c5

Reputation: 53734

What you have actually created here is a Many to Many relationship and in django it's supported with the ManyToManyField

case 1, Patient_Responses has only the two foreign keys.

You don't need this model. Simply delete it and add a ManyToManyField on one of the remaining models to simplify your code and to gain access to the set of features provided by this field

class Patient_Names(models.Model):
    ...
    questions = models.ManyToManyField(Doctor_Questions)

case 2, Patient_Responses has fields other than the two foreign keys.

Now you can't delete the Patient_Responses model but you can still unlock the ManyToManyFields benefits by declaring it as a Through Model

questions = models.ManyToManyField(Doctor_Questions, through='Patient_Responses')

Upvotes: 1

Related Questions