试图在Django中搜索记录

时间:2013-08-27 16:17:22

标签: python django search

尝试在django中构建一个简单的搜索页面。

我有一个模特:

class Person(models.Model):
    ROLE_CHOICES = (
        ('Eng', 'Engineering'),
        ('Product', 'Product'),
        ('QA', 'QA'),
        ('Mrkt', 'Marketing'),
        ('Fin/Off', 'Finance / Office'), \
        ('Care', 'Care'),
        ('Sales', 'Sales'),
        )
    ROLE_TYPE = (
        ('Full', 'Full Time'),
        ('CooP', 'Co-Op'),
        ('Part', 'Part Time'), 
        ('Intern', 'Intern'),
        )

    first_name = models.CharField(blank=True, max_length=100)
    last_name = models.CharField(blank=True, max_length=100)
    date_added = models.DateField(auto_now_add=True)
    date_start = models.DateField(auto_now=False)
    date_leaving = models.DateField(auto_now=False)
    role = models.CharField(max_length=100, default = "", choices = ROLE_CHOICES)
    manager = models.ForeignKey('self', limit_choices_to = {'is_manager': True}, null=True, blank=True)
    title = models.CharField(blank=True, max_length=100)
    role_type = models.CharField(max_length=100, default = "", choices = ROLE_TYPE)
    laptop_needed = models.BooleanField(default=True)
    phone_needed = models.BooleanField(default=True)
    desk_loco = models.CharField(blank=True, max_length=100)
    mail_lists = models.ManyToManyField(Mailists, blank=True, null=True)
    notes = models.CharField(blank=True, max_length=500)
    is_manager = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    is_leaving = models.BooleanField(default=False)

    def __unicode__(self):
        return u'%s %s' % (self.first_name, self.last_name)

我有这个观点:

def search_people(request):
    if request.method == 'POST':
        search_text = request.POST['search']
    else:
        search_text = ''

    persons=Person.objects.filter(last_name__contains=search_text)

    return render(request, 'hireterm/search.html', {'persons': persons})

从这种形式中获取:

            <form class="searchfield" method="get" action="/search/" autocomplete="off">
              Search: <input type="text" name="search">
              <input id="searchbuttonmain" type="submit" class="subbtn" value="Search">
            </form>

并呈现此页面:

{% if persons.count %}

{% for p in persons %}
    <p><a href="/edit_person/{{ p.id }}/">{{ p.last_name }}</a><p>
{% endfor %}

{% else %}
    <p> OH NOES <p>
{% endif %}

它总是返回所有Perosns记录,而不是按姓氏过滤的记录,我不知道为什么。我确信我错过了一些微不足道的东西,但我看不到它。感谢您的输入。

1 个答案:

答案 0 :(得分:2)

您的表单方法为GET,但应为POST。这导致它命中else - if语句的一部分。因此,选择了在Person字段中包含空字符串的last_name个对象,但这与所有对象匹配。