Reputation: 881
I want to have a fixed sorting field applied to all custom sortings. To be more specific imagine we have a list of employees, if user choose this form be sorted by hire_date, I want the result be sorted by hire_date and employee_id together. I mean each ordering should be ordered by employee_id inside! For example if we have 5 employees hired today, if hire_date is the sorting field, these 5 be sorted by employee_id and for the other days the same story.
using the following is not the cure. It only sorts them on employee_id when no ordering is set:
queryset = models.Employee.objects.order_by('id')
And this one's result is same as previous:
filter_backends = (CustomFilterSetBackend, filters.OrderingFilter)
custom_filters = (
........
)
ordering_fields = (............)
ordering = ('id',)
tnx a million
Upvotes: 3
Views: 4568
Reputation: 2793
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.
Upvotes: 0
Reputation: 13047
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
.
Upvotes: 5