Natural sort on Django Queryset

后端 未结 2 1640
再見小時候
再見小時候 2021-01-12 10:09

I am working on a system that lists out a range of products sorted by their product code. The product codes are made up of two letters for the followed by a number, for exam

2条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-12 10:24

    Try this

    def alphanumeric_sort(objects_list, sort_key):
        """ Sort a list of objects by a given key
        This function sort a list of objects by a given
        key common across the objects
        Sorting can be implemented on keys that are either
        alphabets, integers or both
        """
        convert = lambda text: int(text) if text.isdigit() else text
        alphanum_key = lambda key: [
            convert(c) for c in re.split("([0-9]+)", getattr(key, sort_key))
        ]
        return sorted(objects_list, key=alphanum_key)
    

提交回复
热议问题