Sorting QuerySet: Typerror ‘<' not supported between instances of 'NoneType' and 'str'

Just sort QuerySet with Django built-in methods, man.

The problems is that if you try to use sorted() or something like that for a QuerySet, say, like this:

a = sorted(mylist, key=lambda x:


a = sorted(mylist, key=operator.attrgetter('label'))

In case your field is None, you will get this error. You can, of course, prepare the QuerySet with something like a @property:

def tag_name(self):
        return ''

And the use it as a key:

a = sorted(mylist, key=lambda x: x.tag_name)

But all this mess sounds to me like trying to build business logic in your Don’t do that. Go to your and make a class method like a grown-up.

def my_sorted_list(cls):
    return MyModel.objects.order_by(self.tag_name)

The best ones are those made for QuerySet. Of course, filter(), order_by(). Looks for others in docs.

Small update: If you need to sort several QuerySets you want to sort, use itertools.chain and sorted():

result_list = sorted(
    chain(page_list, article_list, post_list),
    key=lambda instance: instance.date_created)


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.