如何使用django-extra-views通过相关模型字段进行搜索?

时间:2014-02-11 09:41:05

标签: django django-views

我使用Person模型的外键获得contact对象。联系人有first_name字段。 我如何搜索first_name字段? 机型:

class Person(models.Model):
    (...)
    contact = models.ForeignKey('addressbook.Contact', on_delete=models.CASCADE)
    (...)

class Contact(models.Model):
    last_name = models.CharField("Nazwisko", max_length="40", blank=False)
    first_name = models.CharField("Imię", max_length="40", blank=False) 
    (...)

视图:

class personListPlus(SortableListMixin, SearchableListMixin, ListView):
    model = Person
    search_fields = ['contact__first_name','contact__last_name']
    paginate_by = 20
    template_name = 'list_plus.html'
    sort_fields = ['contact__first_name', 'contact__last_name'                 ]

排序工作正常,但我不知道如何创建GET搜索请求。 我试过http://{VIEW_URL}?q=contact__first_name=ADAM 但作为回应我得到了:Related Field has invalid lookup: icontains 我做错了什么?

2 个答案:

答案 0 :(得分:1)

较新版本的django具有安全功能,可防止在相关模型上进行查找。 解决方法可以在这个问题上找到: Django: Filtering by %filter% not allowed

答案 1 :(得分:1)

您无法指定在URL的查询参数中搜索哪些字段。您的网址应如下所示:

http://{VIEW_URL}?q=ADAM

这将在 contact__first_name contact__last_name 字段中进行搜索,因为这些字段是您视图的* search_field *属性指定的字段。

您可以查看SearchableListMixin类的 get_queryset 方法,了解如何解析查询以及该类如何处理查询参数和搜索字段。