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: x.tag.name)

Or:

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:

@property
def tag_name(self):
    try:
        return self.tag.name
    except:
        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 views.py. Don’t do that. Go to your models.py and make a class method like a grown-up.

@classmethod
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)

References

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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.