Monday, April 20, 2020

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

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?

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/4832d1e1-0acd-45dd-a56c-f1e89f4bcc96%40googlegroups.com.

No comments:

Post a Comment