开发者

Sorting a filtered list in ascending/descending order in django

开发者 https://www.devze.com 2023-02-17 03:30 出处:网络
I have created an Employee management system using Django. I have done a filtering method in it and is based on a choice selected from a drop down menu and a text input. the filtering is working fine.

I have created an Employee management system using Django. I have done a filtering method in it and is based on a choice selected from a drop down menu and a text input. the filtering is working fine. On the first page it gives the entire employee list whic开发者_如何学Pythonh can be shown in both ascending and descending order. On the same page is given the filtering method. The filtered data is shown in another page. Now i want to give a button on the filtered data page, clicking on that button shows the data in ascending/descending. I have written a separate function for ascending and descending in views for the full employee listing. How can it be used for this functionality. I will paste my code here. Please help me to find a solution as i am new to django programming.

I have given 2 separate images for ascending and descending.I want it this way: Clicking on 1 image lists in ascending order; and clicking on other image lists it in descending order.

Filter()

def filter(request):
    val3='' 
    if request.GET.has_key('choices'):
        val2=request.GET.get('choices')
    if request.GET.has_key('textField'):
        val3=request.GET.get('textField')
    if request.POST:
        val2=request.POST.get('choices')    
        val3=request.POST.get('textField')
    if val2=='Designation':                
        newData = EmployeeDetails.objects.filter(designation=val3) 
        flag=True 
    elif val2=='Name':
        newData = EmployeeDetails.objects.filter(userName__icontains=val3)
        flag=True 
    elif val2=='EmployeeID':
        newData = EmployeeDetails.objects.filter(employeeID=val3)  
        flag=True       
    elif val2=='Project':
        newData = EmployeeDetails.objects.filter(project=val3)   
        flag=True   
    elif val2=='DateOfJoin':
        newData = EmployeeDetails.objects.filter(dateOfJoin=val3) 
        flag=True       
    else:
        return HttpResponseRedirect('/employeeList/')    
    #tableList = EmployeeDetails.objects.all()
    paginator = Paginator(newData, 10)    
    try:
         page = int(request.GET.get('page', '1'))
    except ValueError:
        page = 1
    try:
        contacts = paginator.page(page)
    except (EmptyPage, InvalidPage):
        contacts = paginator.page(0)               
    return render_to_response('filter.html',{'newData':newData,'emp_list': contacts,'val2':val2,'val3':val3,'flag':flag})        

filter.html

<div>
Employees List&nbsp;&nbsp;
<a STYLE="text-decoration:none" align=center href="http://10.1.0.90:8080/sortAscend/ "> <img  src="/static/sort_asc.gif " border="1" height="12" /> </a>
<h4 align="left">
{%for data in newData%}
<a STYLE="text-decoration:none" href ="http://10.1.0.90:8080/singleEmployee/{{data.id}}?choices={{val2}}&textField={{val3}}&flag=1 ">
{{ data.userName}}<br>
{%endfor%} 
</h4>
</div>

ascending and descending functions

def sortAscend(request):
    tableList = EmployeeDetails.objects.all().order_by('userName')
    paginator = Paginator(tableList, 12)    
    try:
         page = int(request.GET.get('page', '1'))
    except ValueError:
        page = 1
    try:
        contacts = paginator.page(page)
    except (EmptyPage, InvalidPage):
        contacts = paginator.page(0)
    return render_to_response('sortAscend.html', {'emp_list': contacts})

#Method for listing the employees in descending order
def sortDescend(request):
    tableList = EmployeeDetails.objects.all().order_by('-userName')
    paginator = Paginator(tableList, 12)    
    try:
         page = int(request.GET.get('page', '1'))
    except ValueError:
        page = 1
    try:
        contacts = paginator.page(page)
    except (EmptyPage, InvalidPage):
        contacts = paginator.page(0)
    return render_to_response('sortDescend.html', {'emp_list': contacts})

sortAscending.html

{%for emp in emp_list.object_list%}
    <tr> <td><a STYLE="text-decoration:none" href ="http://10.1.0.90:8080/singleEmployee/{{emp.id}} "> {{ emp.userName }} </a></td> </tr><td>
{%endfor%}


Another alternative to handling sorting in the view level is to do it on the templates. For this reason, you might want to checkout jquery tablesorter (since you are using a table in the display as well). It handles sorting in ascending/descending order.

So if you have the results after filtering that is ready to be displayed to a page, say filtered_results.html, you can do it like this.

<!-- filtered_results.html -->
<head>
   ...
   <script type="text/javascript" src="/path/to/jquery-latest.js"></script> 
   <script type="text/javascript" src="/path/to/jquery.tablesorter.js"></script> 
   <script type="text/javascript">
       $(document).ready(function() {
           $("#myTable").tablesorter();
       });
   </script>
</head>
<body>
    <table id="myTable">
        <thead><tr><th>Some-Label</th></tr></thead>
        <tbody>
        {% for emp in emp_list.object_list %}
            <tr><td><a href="http://10.1.0.90:8080/singleEmployee/{{emp.id}}">{{emp.userName}}</a></td></tr>
        {% endfor %}
        </tbody>
    </table>
</body>

Clicking on the cell of 'Some-Label' will toggle the sorting in ascending/descending order.

Furthermore, it has a plugin for handling pagination. Check out this link for the demo.


I'm not sure I get the question, but if you want to apply the sorting to the filtered objects, you might want to add some sort of caching (different from django's builtin caching), that stores the filtered queryset and sort that. Or you can pass the filter option around using django's session management and redo the sorting query. This would require to refactor filter so the if/elif chain is independant of that view and returns the filtered queryset.

ex:

   def filterHandler(request):
     val3='' 
     if request.GET.has_key('choices'):
        val2=request.GET.get('choices')
     if request.GET.has_key('textField'):
        val3=request.GET.get('textField')
     if request.POST:
        val2=request.POST.get('choices')    
        val3=request.POST.get('textField')
     newData , flag = filter(val2, val3)
     if newData is None:
       return HttpResponseRedirect('/employeeList/')    
     #tableList = EmployeeDetails.objects.all()
     paginator = Paginator(newData, 10)    
     try:
         page = int(request.GET.get('page', '1'))
     except ValueError:
        page = 1
     try:
        contacts = paginator.page(page)
     except (EmptyPage, InvalidPage):
        contacts = paginator.page(0)

     request.session['val2'] = val2
     request.session['val3'] = val3              
     return render_to_response('filter.html',{'newData':newData,'emp_list': contacts,'val2':val2,'val3':val3,'flag':flag})    

    def filter(val2, val3):
      newData = None
      flag = False
      if val2=='Designation':                
        newData = EmployeeDetails.objects.filter(designation=val3) 
        flag=True 
      elif val2=='Name':
        newData = EmployeeDetails.objects.filter(userName__icontains=val3)
        flag=True 
      elif val2=='EmployeeID':
        newData = EmployeeDetails.objects.filter(employeeID=val3)  
        flag=True       
      elif val2=='Project':
        newData = EmployeeDetails.objects.filter(project=val3)   
        flag=True   
      elif val2=='DateOfJoin':
        newData = EmployeeDetails.objects.filter(dateOfJoin=val3) 
        flag=True       
      return newData, flag

Now your sorting methods can get the filter values that was passed originally. Optionally you can add them as get parameters to the views url also.

0

精彩评论

暂无评论...
验证码 换一张
取 消