0

I'm learning django, I am trying to order my objects by field last_name but I think I might be missing something, this is how my function looks:

def list(self, *args, **kwargs):
        data = super().list(*args, **kwargs)
        data = data.data
        x = self.queryset.order_by('last_name')
        print(x)  # I'm priting X but I still get list not ordered by last_name 
        return Response(data)

UPdate

I think what I must do is affect the variable ordering in my Model meta class but I need it to order by lowercase:

class Meta(DRYPermissionModel.Meta):

    ordering = ['username'] # ORDER BY user_name but as if the string was lower case
CommonSenseCode
  • 23,522
  • 33
  • 131
  • 186
  • you can see [this](http://stackoverflow.com/questions/3409047/django-orm-case-insensitive-order-by) link if this helps. – badiya Apr 18 '17 at 13:31

2 Answers2

0

What you are doing wrong here is in self.queryset. You need to make sure that this variable has similar to model.objects.all(). Only then will your order by work.

Hope this helps.

Pansul Bhatt
  • 384
  • 2
  • 5
  • Could you elaborate a bit more on `ORDER BY user_name but as if the string was lower case` – Pansul Bhatt Apr 18 '17 at 11:18
  • the thing is that username can be: Alex.Alexandros or alex.alexandros. I want for it to order as if it was lower case – CommonSenseCode Apr 18 '17 at 11:20
  • So in case of Alex.Alexandros or alex.alexandros, you want the order to be the same i.e. you want your ordering to be case-insensitive. Is that correct? – Pansul Bhatt Apr 18 '17 at 11:24
  • Try using `ordering = [lower('username')]` – Pansul Bhatt Apr 18 '17 at 11:32
  • Perhaps we need to take a step back. Meta class only give so much functionality. Lets look at `self.queryset.order_by('last_name')`. Does that give you some result? If it does, could I get a sample? – Pansul Bhatt Apr 18 '17 at 12:10
0

This is actually what solved my issue:

def list(self, *args, **kwargs):
        """ It returns the list of users ordered by user_name case insentive """
        users = self.queryset.order_by(Lower('username'))
        serializer = serializers.UserSerializer
        return Response(serializer(users, many=True).data)
CommonSenseCode
  • 23,522
  • 33
  • 131
  • 186