结合&订购查询集

时间:2015-04-09 09:44:10

标签: python django django-queryset

我试图将额外的模型添加到有序的项目列表中,并使列表中的所有内容按每个模型上的日期字段排序。

我以为我通过链接每个查询集并用密钥对它们进行排序来破解它;

def get_ordering(obj):
    """
    Helper to get the 'order_by' field for the paginated latest news list.
    :param obj: Object used in the paginated latest news
    :type obj: django.db.model
    :return: ordering field
    :rtype: str
    """
    if isinstance(obj, LatestNews):
        return '-publish_date'
    else:
        return '-date_created'


def build_paginated_latest_news(request, instance=None, placeholder=None):

    paginated_page_no = get_page_no(request)
    paginated_page_items = get_page_items(request)
    latest_news = LatestNews.cached.published_items(
        request, instance, placeholder
    )
    query = published_items(request)
    videos = VideoGalleryPlugin.objects.filter(query)
    audio = Audio.objects.filter(query)

    obj_list = sorted(
        chain(latest_news, videos, audio),
        key=lambda instance: get_ordering(instance)
    )
    paginator = Paginator(obj_list, paginated_page_items)

但最终呈现的列表最终显示为视频,音频,latest_news,即使是我将它们链接在一起的顺序也是如此。

使用sorted()将这样的密钥应用于组合查询集是否正确?

1 个答案:

答案 0 :(得分:1)

get_ordering()中,您应该返回排序函数将使用的值:

def get_ordering(obj):
    if isinstance(obj, LatestNews):
        return obj.publish_date
    else:
        return obj.date_created

然后在你看来:

obj_list = sorted(
    chain(latest_news, videos, audio),
    key=get_ordering, # intermediate lambda is not needed here
    reverse=True
)