[英]Access Foreign Key Field in Django
This is my models.py
file:这是我的
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
In views.py
I am trying to access the first_name
of a Patient
object, based on Appointment
.在
views.py
中,我试图根据Appointment
访问Patient
object 的first_name
。 So, for example, let's say that I have an appointment with a known id
, and I want to get the first_name
of the patient
who has that appointment.因此,例如,假设我有一个已知
id
的约会,并且我想获取有该first_name
的patient
的名字。
How would I do this in Django?我将如何在 Django 中执行此操作? I know only how to access a patient's appointment, but I can't figure out how to access an appointment's patient.
我只知道如何访问患者的预约,但我不知道如何访问预约的患者。
According to your Model design a Appointment
has many Patient
.根据您的 Model 设计一个
Appointment
有很多Patient
。 Basically what you can do to access a Appointment's
Patients
is add _set
suffix on the reverse relation like following基本上,您可以做些什么来访问
Appointment's
Patients
是在反向关系上添加_set
后缀,如下所示
appointment.patient_set.all()
Filter patients with the known appointment id.过滤具有已知预约 ID 的患者。 Do something like this in your views.
在你的观点中做这样的事情。
appointment = get_object_or_404(Appointment, pk = appointment_id)
patient = Patient.objects.filter(appointments=appointment)
patient__first_name
for condition also you can use for example:对于条件,您也可以使用例如:
Q(patient__first_name__icontains='John')
note that patient
is lowercase注意
patient
是小写的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.