Skip to main content
 首页 » 编程设计

python之Django ORM : filter primary model based on chronological fields from related model

2025年05月04日45tintown

让我们假设我们有以下模型:

class Patient(models.Model) 
    name = models.CharField() 
    # other fields following 
 
class MedicalFile(model.Model) 
    patient = models.ForeignKey(Patient, related_name='files') 
    date = models.DateField() 
    diagnostic = models.CharField() 

我们想为患者构建一个 View 集,我们希望根据他们最后可用/有效的诊断来过滤患者记录。

如果不使用原始 SQL,我不知道如何解决这个问题。是否有仅使用 Django 查询集语法构建此语句的最佳方法?


我是如何解决这个问题的?

我敢肯定这不是很好,但它是过滤大型数据集的最佳选择。

我们的想法是使用在数据库层实现的 View ,我们将在其中查询所有患者及其关联的最新医疗文件,而不是将 Django 实体映射到该 View 。当然,我们将使新模型成为非托管模型。

为什么要走这么远的路?因为在新模型上我们可以使用“可重用”的 Django 查询语法。当然,数据库中的 View 不可重复使用,必须为每个数据库后端解决方案重新创建。

考虑到 Postgres,这将是 View 定义:

SELECT 
    p.*, 
    f.* 
FROM Person p 
    LEFT JOIN ( 
        SELECT 
            *, 
            max(date) OVER (PARTITION BY person_id) AS latest_date 
        FROM MedicalFile 
    ) AS mf ON mf.person_id = p.person_id 
WHERE 
    mf.latest_date IS NULL OR mf.latest_date = mf.date 

然后我们可以像这样创建关联模型

class LatestMedicalFile(models.Model): 
    patient = models.OneToOneField(Patient, related_name="latest_file") 
    date = models.DateField() 
    diagnostic = models.CharField() 
 
    class Meta: 
        managed = False 
        db_table = '<your view name here>' 

最后,我们的查询可以这样写:

Patient.objects.filter(latest_file__diagnostic='flu') 

在我看来,这既不直观,也不干净。有什么想法吗?

请您参考如下方法:

如果您有兴趣查看这些文件:

MedicalFile.objects.annotate( 
    maxdate=Max( 
        'patient__files__date' 
        )).filter( 
            maxdate=F('date'), 
            diagnosis="flu").select_related( 
                'patient' 
            ) 

如果你想要患者:

Patient.objects.annotate( 
    maxdate=Max( 
        'files__date' 
        )).filter( 
            maxdate=F('files__date'), 
            files__diagnosis="flu")) 

非常感谢Roba ,协作提问/回答是我最喜欢的 SO 用户类型。