Django基于url参数对模板中的对象进行排序和过滤

z31licg0  于 2023-03-04  发布在  Go
关注(0)|答案(2)|浏览(118)

我的问题是关于排序和过滤对象在。html模板。我有两个功能的工作,但如果我使用其中之一,那么第二个是不工作的。
我的模板:

<form action="{% url 'adverts' %}" method="get">
    <div class="form_field">
        <label for="formInput#search">Search Adverts</label>
        <input style="width: 400px;" class="input input--text" id="formInput#search"
               type="text" value="{{search_query}}" name="search_query" placeholder="Search by Adverts title, brand or description">
    </div>
</form>

<main>
<div class="search">
    <h2>Number of adverts: {{num}}</h2>
    <form action="{% url 'adverts' %}">
        <span>Sort by:</span>
        <select name="sort">
          <option value="new">newest</option>
          <option value="old">older</option>
          <option value="price_low">price low</option>
          <option value="price_high">price high</option>
          <option value="mileage_low">mileage lowest</option>
          <option value="mileage_high">mileage higher</option>
          <input type="submit" value="Sort">
        </select>
      </form>

{% for advert in adverts %}
<div class="mainAdvert">
    <a href="{% url 'single-advert' advert.id %}">
    <div class="row">
        <div class="column">
            <img src="{{ advert.featured_image.url }}" class="advertImage">
        </div>
        <div class="column1">
            <span class="titleAdvert"><b>{{advert.title}}</b></span>
                <ul>
                    <li class="header">{{advert.year_of_production}}</li>
                    <li class="header">{{advert.mileage}}km</li>
                    <li class="header">{{advert.fuel_type}}</li>
                    <li class="header">{{advert.variant}}</li>
                    <li class="header">{{advert.created}}</li>
                </ul>
                <span class="location"><img class="address-icon" src="images/pin.png" alt="" /><b>Adres: </b>Rogowo, Poland</span>
        </div>
        <div class="column">
            <span><h2 class="price">{{advert.price}}PLN</h2></span>
        </div>
    </div>
    </a>
</div>
{% endfor %}

我的www.example.com功能:views.py function:

def adverts(request):
    page = 'adverts'
    adverts, search_query = searchAdverts(request)

    adverts = Advert.objects.all()
    sort_by = request.GET.get('sort')

    if sort_by == 'new':
        adverts = Advert.objects.all().order_by('-created')
    elif sort_by == 'old':
        adverts = Advert.objects.all().order_by('created')
    elif sort_by == 'mileage-high':
        adverts = Advert.objects.all().order_by('-mileage')
    elif sort_by == 'mileage-low':
        adverts = Advert.objects.all().order_by('mileage')
    elif sort_by == 'power-high':
        adverts = Advert.objects.all().order_by('-power')
    elif sort_by == 'power-low':
        adverts = Advert.objects.all().order_by('power')
    else:
        adverts = Advert.objects.all().order_by('-created')

    num = len(adverts)
    context = {'adverts': adverts, 'num': num, 'page': page, 'search_query': search_query}
    return render(request, 'adverts/adverts.html', context)

还有我的www.example.com搜索功能utils.py function for searching:

from .models import Advert, Brand
from django.db.models import Q

def searchAdverts(request):
    search_query = ""

    if request.GET.get('search_query'):
        search_query = request.GET.get('search_query')

    brands = Brand.objects.filter(name__icontains=search_query)

    adverts = Advert.objects.distinct().filter(
        Q(title__icontains=search_query) |
        Q(description__icontains=search_query) |
        Q(brand__in=brands)
    )

    return adverts, search_query

我认为问题出在'adverts'变量中。因为我正在将它传递给我的模板。而且我只使用排序中的变量。adverts = Advert.objects.all()我试图更改另一个名称上的'adverts'以进行排序,但我将它传递到了我的模板中。

{% if ... %}
{% for advert in adverts %}
<div class="mainAdvert">
    <a href="{% url 'single-advert' advert.id %}">
    <div class="row">
        <div class="column">
            <img src="{{ advert.featured_image.url }}" class="advertImage">
        </div>
        <div class="column1">
            <span class="titleAdvert"><b>{{advert.title}}</b></span>
                <ul>
                    <li class="header">{{advert.year_of_production}}</li>
                    <li class="header">{{advert.mileage}}km</li>
                    <li class="header">{{advert.fuel_type}}</li>
                    <li class="header">{{advert.variant}}</li>
                    <li class="header">{{advert.created}}</li>
                </ul>
                <span class="location"><img class="address-icon" src="images/pin.png" alt="" /><b>Adres: </b>Rogowo, Poland</span>
        </div>
        <div class="column">
            <span><h2 class="price">{{advert.price}}PLN</h2></span>
        </div>
    </div>
    </a>
</div>
{% endfor %}
{% else ... %}
{% for advert in adverts2 %}
<div class="mainAdvert">
    <a href="{% url 'single-advert' advert.id %}">
    <div class="row">
        <div class="column">
            <img src="{{ advert.featured_image.url }}" class="advertImage">
        </div>
        <div class="column1">
            <span class="titleAdvert"><b>{{advert.title}}</b></span>
                <ul>
                    <li class="header">{{advert.year_of_production}}</li>
                    <li class="header">{{advert.mileage}}km</li>
                    <li class="header">{{advert.fuel_type}}</li>
                    <li class="header">{{advert.variant}}</li>
                    <li class="header">{{advert.created}}</li>
                </ul>
                <span class="location"><img class="address-icon" src="images/pin.png" alt="" /><b>Adres: </b>Rogowo, Poland</span>
        </div>
        <div class="column">
            <span><h2 class="price">{{advert.price}}PLN</h2></span>
        </div>
    </div>
    </a>
</div>
{% endfor %}
{% endif %}

这是一个好主意吗?或者也许我只是需要改变mu函数?我想例如搜索'奥迪'和排序结果从最旧的在同一模板。

fhg3lkii

fhg3lkii1#

当你给同一个变量分配一个新的查询时,你的adverts函数总是覆盖你的searchAdverts。

adverts, search_query = searchAdverts(request)

adverts = Advert.objects.all()
sort_by = request.GET.get('sort')

在这里,您在第一行中将adverts设置为过滤后的查询,然后立即将adverts设置为Advert.objects.all(),使searchAdverts(request)调用变得多余,第一步是停止这样做。
第二,Django的惰性查询使用得很糟糕。你又一次在赋值后重新分配广告,这意味着你在没有使用同一个变量的情况下赋值了3次。当你写广告= Advert.objects.all时()在Django中,你并不是真的调用那个查询,你只是在准备它,这意味着你可以添加更多的过滤器,在初始分配后进行排序等,而无需进行额外的数据库查询,因此您的广告的主要部分可以这样编写:

adverts = Advert.objects.all()
 sort_by = request.GET.get('sort')

 if sort_by == 'old':
        adverts = adverts.order_by('created')
    elif sort_by == 'mileage-high':
        adverts = adverts.order_by('-mileage')
    elif sort_by == 'mileage-low':
        adverts = adverts.order_by('mileage')
    elif sort_by == 'power-high':
        adverts = adverts.order_by('-power')
    elif sort_by == 'power-low':
        adverts = adverts.order_by('power')
    else:
        adverts = adverts.order_by('-created')

这样就可以实际使用adverts = Advert.objects.all()行,并使代码更简洁

djp7away

djp7away2#

是的,这使代码更干净。谢谢帮助。我做了非常简单的更改,我现在有我的函数代码如下:

def adverts(request):
    page = 'adverts'
    search_query = ""

    #searching
    if request.GET.get('search_query'):
        adverts, search_query = searchAdverts(request)
    else:
    #sorting
        adverts = Advert.objects.all()
        sort_by = request.GET.get('sort')

        if sort_by == 'new':
            adverts = adverts.order_by('-created')
        elif sort_by == 'old':
            adverts = adverts.order_by('created')
        elif sort_by == 'mileage-high':
            adverts = adverts.order_by('-mileage')
        elif sort_by == 'mileage-low':
            adverts = adverts.order_by('mileage')
        elif sort_by == 'power-high':
            adverts = adverts.order_by('-power')
        elif sort_by == 'power-low':
            adverts = adverts.order_by('power')
        else:
            adverts = adverts.order_by('-created')

    num = len(adverts)
    context = {'adverts': adverts, 'num': num, 'page': page, 'search_query': search_query}
    return render(request, 'adverts/adverts.html', context)

现在一切都像我想要的那样工作:D

相关问题