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

痞子三分冷 提交于 2020-02-04 05:27:09

问题


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)  

回答1:


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')


来源:https://stackoverflow.com/questions/41715273/django-one-model-has-two-foreign-keys-is-this-the-right-approach-in-this-case

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!