python - Django 中的可排序表格

标签 python django

我阅读了一些关于此的其他帖子以及一些涉及 javascript 和使用其他库的建议。我用手快速做了一些事情,但我对 Django 和 Python 不熟悉,所以我很好奇这是否不是一个好方法。

HTML

 <table>
        <tr>
            <td><a href="?sort=to">To</a></td>
            <td><a href="?sort=date">Date</a></td>
            <td><a href="?sort=type">Type</a></td>
        </tr>
        {% for record in records %}
        <tr><td>{{record.to}}</td><td>{{record.date}}</td><td>{{record.type}}</td></tr>
        {% endfor %}
    </table>

查看

headers = {'to':'asc',
         'date':'asc',
         'type':'asc',}

def table_view(request):
    sort = request.GET.get('sort')
    if sort is not None:
        if headers[sort] == "des":
            records = Record.objects.all().order_by(sort).reverse()
            headers[sort] = "asc"
        else:
            records = Record.objects.all().order_by(sort) 
            headers[sort] = "des"
    else:
        records = Record.objects.all()
    return render_to_response("table.html",{'user':request.user,'profile':request.user.get_profile(),'records':records})

最佳答案

我觉得不错。我建议在 View 代码中进行一次小的重构:

headers = {'to':'asc',
         'date':'asc',
         'type':'asc',}

def table_view(request):
    sort = request.GET.get('sort')
    records = Record.objects.all()

    if sort is not None:
        records = records.order_by(sort)

        if headers[sort] == "des":
            records = records.reverse()
            headers[sort] = "asc"
        else:
            headers[sort] = "des"

    return render_to_response(...)

关于python - Django 中的可排序表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3648512/

相关文章:

python - 使用 python scipy 将 Gamma 分布拟合到数据

python - Defaultdict/没有足够的值来解压

从 Python 调用 Java,无需加载类路径

Django Cookiecutter : How to import AUTH_USER_MODEL in config/settings/base. py?

python - 加速django嵌套for循环时间序列

python - 我应该如何在 Django 应用程序中实现反向 AJAX?

python - 错误消息在 Django 中未按预期工作

python - 更改 pandas 数据帧列中所有行的值

python - "Reset original view"不显示全貌

python - Stripe创建客户一次性收费