首页 > 解决方案 > 搜索功能什么都不返回 - Django

问题描述

def Search(request):
  if request.method == 'GET' and request.GET['x']:
    parameter = request.GET['x']
    results = Category.objects.filter(advert__Seller_Name__icontains = parameter)
    return render(request, 'campusbuy/search.html', {'results': results})

else:
    return render(request, 'campusbuy/search.html')

以上是我的搜索功能。当我尝试在模板中搜索对象时,它什么也不返回。但是,当我故意搜索不在数据库中的 Seller_name 时,它​​会返回 {% else %} 值。下面是模板:

% extends 'campusbuy/base.html' %}

{% block content %}

{% if results %}


    {% for ads in results.advert_set.all %}
        <p>{{ads.Seller_Name }}</p>
        <p>{{ads.Location}}</p>
        <p>{{ads.Description}}</p>
        <p>{{ads.Asking_Price}}</p>

     {% endfor %}

{% else %}
    <p>No Ad matched your search criteria.</p>

{% endif %}


{% endblock %}

这是models.py:

class Category(models.Model):

Name = models.CharField(max_length=20, null=True, blank=True)
Details = models.CharField(max_length=100, default="Default")
Category_Logo = models.ImageField(max_length=100, upload_to='uploads')

def __str__(self):
    return self.Name

class Advert(models.Model):

HALL3 = 'HALL3'
HALL4 = 'HALL4'
HALL2 = 'HALL2'
MAIN_GATE = 'MAINGATE'
HALL1 = 'HALL1'

Location_Choices = (
    (HALL3, 'Hall3'),
    (HALL4, 'Hall4'),
    (HALL2, 'Hall2'),
    (MAIN_GATE, 'Main_gate'),
    (HALL1, 'Hall1')
)

category = models.ForeignKey(Category, on_delete=models.CASCADE)
Seller_Name = models.CharField(max_length=50, blank=False, null=False)
Phone_Number = models.CharField(max_length=11, blank=False, null=False,
                                help_text='<p style="color: red; font: italic 12px tahoma;">**Please input a working Phone Number that you can be contacted with on the fly</p>')
image = models.ImageField(max_length=100, upload_to='uploads')
Item = models.CharField(max_length=20, blank=False, null=False)
Location = models.CharField(max_length=10, choices=Location_Choices, default=HALL3, blank=False)
Description = models.TextField(max_length=250, blank=False, null=False)
Asking_Price = models.CharField(max_length=20, blank=False, null=False)
published_date = models.DateTimeField(blank=False, default=timezone.now)

先感谢您!

标签: djangosearchdjango-templates

解决方案


我仍然不明白您为什么尝试在查询中包含 Category,因为您根本没有在查询本身或模板中使用它。只需直接查询和使用 Adverts:

results = Advert.objects.filter(Seller_Name__icontains=parameter)

并直接对其进行迭代:

{% for ads in results %}
    <p>{{ads.Seller_Name }}</p>
    <p>{{ads.Location}}</p>
    <p>{{ads.Description}}</p>
    <p>{{ads.Asking_Price}}</p>
 {% endfor %}

另请注意,您不需要该if块,因为如果循环是空的for template tag has an [`]( https://docs.djangoproject.com/en/2.1/ref/templates/builtins/#for-empty ) 子句空的:

{% for ads in results %}
    <p>{{ads.Seller_Name }}</p>
    <p>{{ads.Location}}</p>
    <p>{{ads.Description}}</p>
    <p>{{ads.Asking_Price}}</p>
{% empty %}
    <p>No Ad matched your search criteria.</p>
{% endfor %}

推荐阅读