首页 > 解决方案 > 基于两种模型从数据库进行django查询

问题描述

我正在研究搜索页面,医生可以在其中搜索name,start_dateend_date. 这里 start_date 和 end_date 是上传任何文档的日期范围。结果应返回姓名为并且在和name之间上传文件的所有患者。start_dateend_date

class Document(models.Model):
    name = models.CharField(max_length=15, blank=True)
    document = models.FileField(upload_to='documents/')
    uploaded_at = models.DateTimeField(auto_now_add=True)
    patient = models.ForeignKey(to=Patient, on_delete=models.CASCADE, unique=False)
    
    class Meta:
        unique_together = ('name', 'document', 'patient')

    # many document can have same patient

    def __str__(self) -> str:
        return f'{self.name}'
    
    def __repr__(self) -> str:
        return f'{self.name}'

class Patient(models.Model):
    # required fields
    first_name = models.CharField(max_length=55, blank=False, null=False)
    last_name = models.CharField(max_length=55, blank=False, null=False)
    email = models.EmailField(max_length=255, blank=False, null=False, unique=True)
    
    # not required fields
    address = models.TextField(max_length=255, blank=True, null=True)
    postal_zip = models.IntegerField(max_length=255, blank=True, null=True)
    city = models.CharField(max_length=255, blank=True, null=True)
    country = models.CharField(max_length=255, blank=True, null=True)
    phone_number = models.IntegerField(max_length=17, blank=True, null=True) # mobile
    alternate_number = models.IntegerField(max_length=17, blank=True, null=True) # alternate

    def __str__(self) -> str:
        return f"{self.first_name} {self.last_name}"
    
    def __repr__(self) -> str:
        return f"{self.first_name} {self.last_name}"

我可以像这样在特定日期之间上传所有文件

documents  = Document.objects.filter(
                    uploaded_at__gte=start_date
                ).intersection(
                    Document.objects.filter(uploaded_at__lte=end_date)
                )

但我想不出一种将上述结果与此结合的方法

query = Patient.objects.filter(
                    Q(first_name__icontains=search_key)         |
                    Q(last_name__icontains=search_key)          |   
                    Q(email__icontains=search_key)              |
                    Q(city__icontains=search_key)               |
                    Q(phone_number__icontains=search_key)       |
                    Q(alternate_number__icontains=search_key)   |
                    Q(country__icontains=search_key)           
    
                )

标签: pythonsqldjangodjango-formsdjango-queryset

解决方案


您可以使用双下划线来查看关系,因此在这里我们可以过滤Patient具有给定范围内的文档的 s:

# Patients which match the search_key, and have
# documents uploaded in the (start_date, end_date) range

query = Patient.objects.filter(
    Q(first_name__icontains=search_key) |
    Q(last_name__icontains=search_key) |
    Q(email__icontains=search_key) |
    Q(city__icontains=search_key) |
    Q(phone_number__icontains=search_key) |
    Q(alternate_number__icontains=search_key) |
    Q(country__icontains=search_key),
    document__uploaded_at__range=(start_date, end_date)
).distinct()

正如您所评论的.distinct()那样,此处可以防止您多次检索同一患者(Document在该范围内一次)。

Documents 具有Patient与给定条件匹配的 a:

# Documents uploaded in the (start_date, end_date) range
# which match a Patient with the search_key.

query = Document.objects.filter(
    Q(patient__first_name__icontains=search_key) |
    Q(patient__last_name__icontains=search_key) |
    Q(patient__email__icontains=search_key) |
    Q(patient__city__icontains=search_key) |
    Q(patient__phone_number__icontains=search_key) |
    Q(patient__alternate_number__icontains=search_key) |
    Q(patient__country__icontains=search_key),
    uploaded_at__range=(start_date, end_date)
)

推荐阅读