django 如何从另一个模型字段按查询集排序?

jfewjypa  于 2022-12-14  发布在  Go
关注(0)|答案(2)|浏览(128)
class Item(models.Model):
    name = models.CharField(max_length=255)
    user = models.ForeignKey(User)

class Document(models.Model):
   doc_type = models.CharField(max_length=10, default="DOC")
   item = models.ForeignKey(Item, related_name="docs")
   uploaded_at = models.DateTimeField(auto_now_add=True)

@api_view(["GET"])
def get_items(request):
    # docs__uploaded_at should be from objects having doc_type="DOC" only
    # doc = Document.objects.filter(item=item, doc_type="DOC")
    items = Item.objects.prefetch_related("docs").filter(user=request.user).order_by("docs__uploaded_at")

在这里,我想根据文档uploaded_at字段(仅包含doc_type="DOC")对项目查询集进行排序。

bhmjp9jg

bhmjp9jg1#

您可以尝试如下操作。

items = Item.objects.prefetch_related("docs").filter(user=request.user).filter(docs__doc_type = "DOC").order_by("docs__uploaded_at")
w3nuxt5m

w3nuxt5m2#

可以用'DOC'确定最新项目的uploaded_atdoc_type

from django.db.models import F, Max, Q
from django.db.models.functions import Coalesce

@api_view(['GET'])
def get_items(request):
    items = Item.objects.filter(user=request.user).alias(
        latest_upload=Coalesce(
            Max('docs__uploaded_at', filter=Q(docs__doc_type='DOC')),
            F('created_at')
        )
    ).order_by('-latest_upload')
    # …

因此,这里我们确定docsdoc_type='DOC'docs__uploaded_at(最近的),并且在没有项的情况下(那么Max(…)NULL),我们退回到created_at字段。

注意django-1.9April 2017起改为no longer supported [Django-doc],您应该考虑升级Django版本。

相关问题