Ошибка при поиске названия и цены одновременно - PullRequest
0 голосов
/ 12 февраля 2020

У меня есть форма фильтра, где я могу фильтровать контент по категории, названию и цене. Я могу одновременно искать товары по категории и цене или по категории и названию, но получаю сообщение об ошибке при попытке выполнить фильтрацию по цене и названию.

Вот ошибка, что я получаю после фильтрации по цене и названию:

FieldError at /

 Cannot resolve keyword 'current_price' into field. Choices are: category, description, discount_price, id, image, label, orderitem, price, slug, title

views.py

def HomeView(request):
  item_list = Item.objects.all()
  item_list = item_list.annotate(current_price=Coalesce('discount_price', 'price'))

  category_list = Category.objects.all()
  query = request.GET.get('q')

  if query:
      item_list = Item.objects.filter(title__icontains=query)

  cat = request.GET.get('cat')
  if cat:
      item_list = item_list.filter(category__pk=cat)

  price_from = request.GET.get('price_from')
  price_to = request.GET.get('price_to')

  if price_from:
      item_list = item_list.filter(current_price__gte=price_from)

  if price_to:
      item_list = item_list.filter(current_price__lte=price_to)

  paginator = Paginator(item_list, 10)

  page = request.GET.get('page')

  try:
      items = paginator.page(page)
  except PageNotAnInteger:
      items = paginator.page(1)
  except EmptyPage:
      items = paginator.page(paginator.num_pages)

  context = {
      'items': items,
      'category': category_list
  }
  return render(request, "home.html", context)

html:

        <form method="GET" action=".">
        <div class="form-group col-md-4">
            <label for="category">Category</label>
            <select id="cat" class="form-control" name="cat">
                <option value="" selected>Choose...</option>
                <option value="" href="/home">All</option>
                {% for cat in category %}
                <option value="{{ cat.pk }}">{{ cat }}</option>
                {% endfor %}
            </select>

        </div>
        <div class="input-group">
            <input class="form-control py-2 border-right-0 border" type="search" name="q" placeholder="Brand..">
            <span class="input-group-append">
                <div class="input-group-text bg-transparent">
                    <i class="fa fa-search"></i>
                </div>
            </span>
        </div>
        <div class="input-group">
            <input class="form-control py-2 border-right-0 border" type="search" name="price_from"
                placeholder="Price from">
            <span class="input-group-append">
                <div class="input-group-text bg-transparent">
                    <i class="fa fa-search"></i>
                </div>
            </span>
        </div>
        <div class="input-group">
            <input class="form-control py-2 border-right-0 border" type="search" name="price_to"
                placeholder="Price to">
            <span class="input-group-append">
                <div class="input-group-text bg-transparent">
                    <i class="fa fa-search"></i>
                </div>
            </span>
        </div>
        <button type="submit" class="btn btn-primary">Search</button>
    </form>

Ответы [ 2 ]

1 голос
/ 12 февраля 2020

Вероятно, ваша ошибка вызвана

if query:
       item_list = Item.objects.filter(title__icontains=query)

, когда вы перезаписываете item_list с пометкой current_price.

Попробуйте отфильтровать item_list вместо Item.objects.

0 голосов
/ 12 февраля 2020

Вы должны проверить свою модель товара. Сообщение об ошибке говорит вам, что в модели Item нет current_price. Поскольку вы не указали класс Item и в соответствии с сообщением об ошибке, возможно, вы хотите выполнить поиск по 'цене':

if price_from:
    item_list =item_list.filter(price__gte=price_from)

if price_to:
    item_list = item_list.filter(price__lte=price_to)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...