[英]Access Foreign Key Field in 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
中,我試圖根據Appointment
訪問Patient
object 的first_name
。 因此,例如,假設我有一個已知id
的約會,並且我想獲取有該first_name
的patient
的名字。
我將如何在 Django 中執行此操作? 我只知道如何訪問患者的預約,但我不知道如何訪問預約的患者。
根據您的 Model 設計一個Appointment
有很多Patient
。 基本上,您可以做些什么來訪問Appointment's
Patients
是在反向關系上添加_set
后綴,如下所示
appointment.patient_set.all()
請參閱此處的第一個示例。
過濾具有已知預約 ID 的患者。 在你的觀點中做這樣的事情。
appointment = get_object_or_404(Appointment, pk = appointment_id)
patient = Patient.objects.filter(appointments=appointment)
patient__first_name
對於條件,您也可以使用例如:
Q(patient__first_name__icontains='John')
注意patient
是小寫的
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.