![](/img/trans.png)
[英]Python(Django) how to sort a list of objects by timestamp attribute
[英]Sort Django objects by attribute in template
我有一個模型Item,具有幾個屬性,例如名稱,類型和所有者。 在我的模板中,項目列表被遍歷並顯示在表格中。 我想做的是單擊表頭旁邊的按鈕時對表中的項目重新排序,即,單擊“名稱”旁邊的按鈕時,表中的元素按字母順序排序。 這是我的模板:
{% 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 %}
代替按鈕,使用鏈接並將參數傳遞給視圖:
<th><a href="{{ url('myurl') }}?sort=name">Name </a></th>
在django視圖中,您可以使用: request.GET.get('sort', 'your_default_sort')
檢索sort參數request.GET.get('sort', 'your_default_sort')
並使用它對查詢集進行排序。 如果您使用的是FBV,請在函數中手動更改它,如果您使用的是CBV,則只需重寫類的get_ordering()
方法
然而,這將我像一個客戶端解決方案相比,更容易的DataTable
希望這可以幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.