在Django中访问外键字段

时间:2020-06-10 01:26:44

标签: python 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。因此,举例来说,假设我有一个已知的id约会,并且我想从拥有该约会的first_name中获得patient

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

2 个答案:

答案 0 :(得分:0)

根据模型设计,Appointment有许多Patient。基本上,访问Appointment's Patients所要做的就是在反向关系上添加_set后缀,如下所示

appointment.patient_set.all()

请参见第一个示例here

答案 1 :(得分:0)

过滤具有已知约会ID的患者。在您的视图中执行类似的操作。

appointment = get_object_or_404(Appointment, pk = appointment_id)   
patient = Patient.objects.filter(appointments=appointment)