[Django]-Django rest framework an always sorting field

5👍

In model add this:

class Employee(models.Model):
    ......
    ......

    class Meta:
        ordering = ['-hire_date','employee_id']

It will order by hire_date and if dates are same then employee_id.

0👍

Same problem i had got back while working so , there are few solutions you can adopt ,
In your Employee model class you can do these ,

from __future__ import unicode_literals
from django.db import models

class Employee(models.Model):
    ....
    ....
    class Meta:
    # Latest by hire_date ascending, employee_id ascending.

        ordering = ['hire_date', 'employee_id']

And also you can do some thing like these at query end ,

from your_app.models import Employee
queryset = models.Employee.objects.order_by('employee_id')

Third solution can be combined form of first two solutions as i mentioned and as you described in comment that can be like ,

from __future__ import unicode_literals
from django.db import models

class Employee(models.Model):
    ....
    ....
    class Meta:
    # Latest by hire_date ascending, employee_id ascending.

        ordering = ['employee_id']

Now when you fetch employee you should do these ,
(i am assuming these from views.py file)

from your_app.models import Employee
queryset = models.Employee.objects.order_by('hire_date')

Let me know if any problem in third approach.

Leave a comment