这是我的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中执行此操作?我只知道如何访问患者的约会,但我不知道如何访问约会的患者。
答案 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)