Django筛选最新文件

2024-05-16 20:44:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个像

class Type(CommonBase):
    """
        Allowed document types
    """
    DOCUMENT_CLASS_CHOICES = (
        ('C', 'Credit Card'),
        ('D', 'Debit Card'),
        ('SD', 'Supporting Documents'),
    )
    MODEL_TYPE_CHOICE = (
        ('person', 'Person'),
        ('bank', 'Bank'),
        ('all', 'All')
    )
    document_title = models.CharField(max_length=100)
    document_class = models.CharField(choices=DOCUMENT_CLASS_CHOICES, max_length=3, default='C')
    model_type = models.CharField(choices=MODEL_TYPE_CHOICE, max_length=50, default='person')

class Document(CommonBase):
  
    doc_type = models.ForeignKey(Type, on_delete=models.PROTECT)
    uploaded_datetime = models.DateTimeField(null=True, blank=True)
    user = models.ForeignKey(Person, on_delete=models.CASCADE)
    comment = models.CharField(max_length=200, null=True, blank=True)

我可以针对同一用户上传多张信用卡或多张借记卡的详细信息

因此,如果用户上载了2个信用卡文档和3个借记卡文档。 我需要得到所有的文件上传对该用户,但应该只有一个信用卡和借记卡的文件,这是最新的

docs = Documrnt.objects.filter(user=user)

这将为我提供针对该特定用户上传的所有文档(2个信用卡文档和3个借记卡文档)。 但我只需要在结果中最新上传的借记卡和信用卡详细信息

查询应该是怎样的


Tags: 用户文档truemodelstype信用卡documentlength
3条回答

这可以通过使用lookups through relationships,根据所需字段uploaded_datetime排序,然后从每个查询中检索last values来实现。如下例所示:

qs = Document.objects.filter(user=user)
latest_uploaded_credit_card = qs.filter(doc_type__document_class='C').order_by('uploaded_datetime').last()
latest_uploaded_debit_card = qs.filter(doc_type__document_class='D').order_by('uploaded_datetime').last()

您需要的是order_by的递减行为

最早的项目优先。

Document.objects.order_by('uploaded_datetime')

首先是最新项目。(您想要什么)

Document.objects.order_by('-uploaded_datetime')
qs = Document.objects.filter(user=user)
latest_credit_card = qs.filter(doc_type__document_class='C').order_by('-id')[0]
latest_debit_card = qs.filter(doc_type__document_class='D').order_by('-id')[0]

相关问题 更多 >