搜索函数什么也不返回-Django

时间:2018-11-28 18:57:40

标签: django search django-templates

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)

提前谢谢!

1 个答案:

答案 0 :(得分:0)

我仍然不明白为什么要尝试在查询中包括Category,因为在查询本身或模板中根本没有使用它。只需查询并直接使用广告即可:

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 [ empty`](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 %}