MattBroach / DjangoRestMultipleModels

View (and mixin) for serializing multiple models or querysets in Django Rest Framework
MIT License
549 stars 67 forks source link

Better handling of sorting values #21

Closed softzer0 closed 7 years ago

softzer0 commented 7 years ago

For example, when the field value is null it would give the following error on this line: unorderable types: NoneType() < str(). In my case I'm using DateTimeField type as the sorting field, which can contain None sometimes. Also, it would be very useful once it has a support for specifying multiple sorting fields.

MattBroach commented 7 years ago

Hey @MikiSoft-- Sorry for a delayed response -- this answer is probably months too late, but I didn't have a chance to do much maintenance work on this package. Hopefully there will be something helpful here.

The problem with None results in Python 3 is that there's no real generalized way to handle them -- this StackOverflow answer gives a pretty good explanation of the problem. The solution provided can't really be generalized, though -- if you return an empty string instead of None, that will cause the same type error if a user is sorting a numeric field with None (rather than a string-based field with None).

However, the MultipleModelAPIView allows the user to override the queryList_sort function to implement custom sorting. Here's a simplified example that would address the None issue -- you'd probably need to tailor it more (for example: I didn't replicate the sort_descending functionality of the original sorting function -- you can look at the MultipleModeMixin source to figure out how to implement that if you need to):

class CustomSortingView(MultipleModelAPIView):
    queryList = (
        ...
    )
    flat = True
    sorting_field = 'my_field_with_nulls'

    def queryList_sort(self, results):
          field = self.sorting_field
          return sorted(results, key=lambda x: x[field] if x[field] else "")