首页 > 解决方案 > 在 Django 中访问外键字段

问题描述

这是我的models.py文件:

class Appointment(models.Model):                  
    time = models.TimeField(auto_now_add=False, auto_now=False, null=True, blank=True)
    date = models.DateField(auto_now_add=False, auto_now=False, blank=True, null=True)
    employees = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
    location = models.CharField(max_length=100, blank=True, null=True)

    def __str__(self):
        return self.location

class Patient(models.Model):
    first_name = models.CharField(max_length=60, null=True)
    last_name = models.CharField(max_length=60, null=True)
    appointments = models.ForeignKey(Appointment, on_delete=models.CASCADE)

    def __str__(self):
        return self.first_name

views.py我试图访问first_name一个Patient基于Appointment. 因此,例如,假设我与一个 known 有约会id,并且我想获得那个约会first_name的人。patient

我将如何在 Django 中执行此操作?我只知道如何访问患者的预约,但我不知道如何访问预约的患者。

标签: pythondjango

解决方案


根据你的模型设计一个Appointment有很多Patient。基本上,您可以访问 aAppointment's Patients是在反向关系上添加_set后缀,如下所示

appointment.patient_set.all()

请参阅此处的第一个示例。


推荐阅读