Django如何通过GET请求进行排序和过滤

时间:2012-10-14 19:13:48

标签: django filter request chaining

当我选择订购时,我无法真正自动包含每页过滤器。 如何让这些过滤器彼此“可见”?我需要包括或阅读什么?

这是我的view.py

的一小部分
if order == 'asc':
    p = p.order_by('name')
elif order == 'desc':
    p = p.order_by('-name')
elif order == 'price_asc':
    p = p.order_by('price_netto')
elif order == 'price_desc':
    p = p.order_by('-price_netto')
else:
    p.order_by('name')

if limit == "12":
    per_page = "12"
elif limit == "24":
    per_page = "24"
elif limit == "48":
    per_page = "48"
else:
    from endless_pagination.settings import PER_PAGE
    per_page = PER_PAGE

HTML

        <select onchange="location = this.options[this.selectedIndex].value">
            <option value="">--- Sortowanie ---</option>
            <option rel="order" value="?order=desc">Malejąco według nazwy</option>
            <option rel="order" value="?order=asc">Rosnąco według nazwy</option>
            <option rel="order" value="?order=price_asc">Rosnąco według ceny</option>
            <option rel="order" value="?order=price_desc">Malejąco według ceny</option>
        </select>
        Produktów na stronę:
        <a rel="limit" href="?limit=12">12</a>, <a rel="limit" href="?limit=24">24</a>, <a rel="limit" href="?limit=48">48</a>

1 个答案:

答案 0 :(得分:0)

为什么不使用javascript,jquery。您需要一个能够读取查询字符串并覆盖您正在更改的项目的函数。

    <select id="sort-dropdown">
        <option value="">--- Sortowanie ---</option>
        <option rel="order" value="desc">Malejąco według nazwy</option>
        <option rel="order" value="asc">Rosnąco według nazwy</option>
        <option rel="order" value="price_asc">Rosnąco według ceny</option>
        <option rel="order" value="price_desc">Malejąco według ceny</option>
    </select>
    Produktów na stronę:
    <a rel="limit" id="limit-12" href="#">12</a>, <a rel="limit" id="limit-24" href="#">24</a>, <a rel="limit" id="limit-48" href="#">48</a>

然后javascript将如下所示:

function getParameterByName(name)
{
  name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
  var regexS = "[\\?&]" + name + "=([^&#]*)";
  var regex = new RegExp(regexS);
  var results = regex.exec(window.location.search);
  if(results == null)
    return "";
  else
    return decodeURIComponent(results[1].replace(/\+/g, " "));
}
function redirect(order, limit) {
  window.location.url = "?order=" + order + "&limit=" + limit;
}

$("#sort-dropdown").change(function () {
  redirect($(this).val(), getParameterByName("limit"));
});

$("#limit-12").change(function () {
  redirect(getParameterByName("order"), "12");
});

$("#limit-24").change(function () {
  redirect(getParameterByName("order"), "24");
});

$("#limit-48").change(function () {
  redirect(getParameterByName("order"), "48");
});