[Django]-Sort two different models on differently named fields

4👍

So, if your plan is to sort the union of the two querysets, you have to use the sorted method. I would go for something like:

sorted(chain(posts_type1, posts_type2), 
       key=lambda x: x.created_date if isinstance(x, PostType1) 
                                    else x.publish_date)

1👍

Each query can perform the sorting using order_by:

posts_type1 = PostType1.objects.all().order_by('-created_date')
posts_type2 = PostType2.objects.all().order_by('-publish_date')

If you want the whole result to be sorted, you could use a custom iterator instead of chain. An example for two models only (though not necessarily the cleanest one):

def chain_ordered(qs1, qs2):
    next1 = qs1.next()
    next2 = qs2.next()
    while next1 is not None or next2 is not None:
        if next1 is None: yield next2
        elif next2 is None: yeild next1
        elif next1 < next2:
            yield next1
            try:
                next1 = qs1.next()
            except StopIteration:
                next1 = None
        else:
            yield next2
            try:
                next2 = qs2.next()
            except StopIteration:
                next2 = None

StefanoP’s suggestion of using sorted will work too, but AFAIK it will retrieve all items from database during the sorting, which may or may not be a concern to you.

Leave a comment