How to sort a column by Django model method using django-sortable-listview (SortableListView)?

29 views
Skip to first unread message

Nancy Jenifer Benita S

unread,
Apr 20, 2020, 11:08:25 AM4/20/20
to Django users
Using django-sortable-listview package, I'm using SortableListView to sort out all the model fields. In my case, more than model fields, I want to sort it out by model method too.

 
Models.py

class Employee(models.Model):
      name = models.CharField()
      designation = models.CharField()
      company = models.ForeignKey(Company)
      team = models.CharField()
      
      # method
      def team_count(self):
        count = len(Employee.objects.filter(team=self.team))
        return count



Views.py 

class EmployeeListView(SortableListView, generic.list.ListView):

    allowed_sort_fields = {'name': {'default_direction': '', 'verbose_name': 'Employee Name'},
                           'designation': {'default_direction': '', 'verbose_name': 'Designation'},
                           'team': {'default_direction': '', 'verbose_name': 'Team Name'},
                           'team_count()': {'default_direction': '', 'verbose_name': 'No of Team members'}}
    default_sort_field = 'name'
    queryset = Employee.objects.all()
    paginate_by = 10


On the above example, I want to list out Employee name, designation, team name and count of team members.

Anybody help me to sort 'team_count' column?

Reply all
Reply to author
Forward
0 new messages