是否可以在Django中将类作为模型字段?

时间:2016-09-23 13:43:35

标签: django model field

我目前正在尝试在Django中创建一个健康网络网站。 我的想法是在我的注册申请中会有一个名为User的类。存储在User内的状态之一是用户注册的医院。

我在注册应用中创建了另一家医院。我想将该模型医院用作hospital_used状态的模型字段之一。我怎么做?下面是我的UML的一部分,说明了这种关系 UML Diagram

Below is a portion of my UML that illustrates the relationship PNG

到目前为止,这是我的代码。用星号封装的代码是我需要帮助的。

class Hospital(models.Model):
    hospital_Name = models.CharField(max_length=150)

    def __str__(self):
        return "Hospital Name: " + str(self.hospital_Name)


class User(models.Model):
    PATIENT = 'Pat'
    DOCTOR = 'Doc'
    NURSE = 'Nurse'
    ADMINISTRATOR = 'Admin'
    user_type_choice = {
        (PATIENT, 'Patient'),
        (DOCTOR, 'Doctor'),
        (NURSE, 'Nurse'),
        (ADMINISTRATOR, 'Administrator'),
    }

    name = models.CharField(max_length=50)
    dob = models.DateField(auto_now=False)
    username = models.CharField(max_length=50)
    *preferred_hospital = Hospital(models.CharField(max_length=50))*
    patient_type = models.CharField(
        max_length=5,
        choices=user_type_choice,
    )

谢谢StackOverflow好友

1 个答案:

答案 0 :(得分:0)

我建议您阅读有关如何创建简单模型的材料on tutorials

这里你想要的是使用ForeignKey方法。

name = models.CharField(max_length=50)
dob = models.DateField(auto_now=False)
username = models.CharField(max_length=50)
preferred_hospital = models.ForeignKey(Hospital, on_delete = models.CASCADE)
patient_type = models.CharField(
    max_length=5,
    choices=user_type_choice,
)

您不必使用on_delete = models.CASCADE,但最好能够处理删除医院时应该发生的事情。

知道您还可以拥有OneToOne,ManyToOne或ManyToMany字段,这些字段都是here所描述的。

相关问题