Combining & ordering querysets

markwalker_

I'm trying to add extra models to an ordered list of items and have everything in the list ordered by a date field on each model.

I thought I'd cracked it by chaining each queryset and sorting them with a key;

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)

But ultimately the list that's rendered is displayed as videos, audio, latest_news which isn't even the order I chain them all together.

Is it correct to apply a key like this with sorted() to combine querysets?

catavaran

In the get_ordering() you should return the value which will be used by the sorting function:

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

And then in your view:

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

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related