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
. 因此,例如,假设我与一个 known 有约会id
,并且我想获得那个约会first_name
的人。patient
我将如何在 Django 中执行此操作?我只知道如何访问患者的预约,但我不知道如何访问预约的患者。
解决方案
根据你的模型设计一个Appointment
有很多Patient
。基本上,您可以访问 aAppointment's
Patients
是在反向关系上添加_set
后缀,如下所示
appointment.patient_set.all()
请参阅此处的第一个示例。
推荐阅读
- android - 如何获取图像视图的触摸点
- meteor - 在我的应用程序中运行流星会引发错误:ENOENT:没有这样的文件或目录
- javascript - 有没有办法使用函数的参数来使用点符号定位对象中的项目?
- javascript - Javascript var在计算中不起作用
- sql-server - 根据插入的 scope_identity() 在 SQL Server 中设置列的值
- algorithm - 计算最佳情况、平均情况和最坏情况的算法复杂度
- html - HTML 附件仅对使用 Outlook 应用程序(非默认邮件应用程序)的 iPhone 用户变为纯文本
- android - Kotlin:无法重新分配 LatLng 的纬度/经度
- python - 如何根据列表中的值在字典列表中查找字典?
- python - 处理/加载巨大的 gzip 文件到 hive