简体   繁体   English

按模板中的属性对Django对象进行排序

[英]Sort Django objects by attribute in template

I have a model, Item, with several attributes such as name, type, and owner. 我有一个模型Item,具有几个属性,例如名称,类型和所有者。 In my template the list of Items is iterated through and displayed in a table. 在我的模板中,项目列表被遍历并显示在表格中。 What I would like to do is reorder the items in the table when a button next to the table head is clicked ie when the button next to Name is clicked the elements in the table are sorted by alphabetical order. 我想做的是单击表头旁边的按钮时对表中的项目重新排序,即,单击“名称”旁边的按钮时,表中的元素按字母顺序排序。 Here is my template: 这是我的模板:

{% extends 'inventory/base.html' %}

{% block content %}
<a class="btn btn-default" href="{% url 'inventory:entry' %}">New Item</a>
<script>
    jQuery(document).ready(function($) {
    $(".clickable-row").click(function() {
        window.location = $(this).data("href");
    });
});
</script>
{% if item_list %}
    <table>
        <tr>
            <th>Name <button class="btn btn-default" href="order_table"></button></th>
            <th>Type <button class="btn btn-default" href="order_table"></button></th>
            <th>Barcode/Model No. <button class="btn btn-default" href="order_table"></button></th>
            <th>Owner <button class="btn btn-default" href="order_table"></button></th>
            <th>Edit <button class="btn btn-default" href="order_table"></button></th>
        </tr>
        {% for item in item_list %}
            <tr class="clickable-row itemrow" data-href="{% url 'inventory:details' item.id %}">
                <td>{{ item.name }}</td>
                <td>{{ item.itemType }}</td>
                <td>{{ item.barcode }}</td>
                <td>{{ item.owner.username }}</td>
                <td><a href="{% url 'inventory:edit' item.id %}" class="btn btn-default">Edit</a></td>
            </tr>
        {% endfor %}
    </table>
{% endif %}
{% endblock %}

instead of a button use a link and pass a parameter to the view: 代替按钮,使用链接并将参数传递给视图:

<th><a href="{{ url('myurl') }}?sort=name">Name </a></th>

in the django view you can retrieve the sort parameter using : request.GET.get('sort', 'your_default_sort') and use it to order the queryset. 在django视图中,您可以使用: request.GET.get('sort', 'your_default_sort')检索sort参数request.GET.get('sort', 'your_default_sort')并使用它对查询集进行排序。 If you're using FBV change it manually in the function, and if you're using CBV just override the get_ordering() method of your class 如果您使用的是FBV,请在函数中手动更改它,如果您使用的是CBV,则只需重写类的get_ordering()方法

however, It would me much much easier with a client-side solution like datatables 然而,这将我像一个客户端解决方案相比,更容易的DataTable

Hope this helps 希望这可以帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM