欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Django 全文检索haystack实现重载context内容

程序员文章站 2022-06-12 19:58:36
...

第一次翻官方文档,确实比看别人写的博客管用多了,看博客说重载extra_context(),然后写了继承调用不出来,博客里面说什么降低haystack版本就可以继承出来,我都觉得这不是开玩笑吗,个人认为高版本代码跑起来总比低版本代码效率高吧,所以不要去降什么库不至于朋友们,还是要尝试下翻官方文档。

https://django-haystack.readthedocs.io/en/master/

'''
官方文档代码
重载context: get_context_data()
# do something
'''
# views.py
from datetime import date

from haystack.generic_views import SearchView

class MySearchView(SearchView):
    """My custom search view."""

    def get_queryset(self):
        queryset = super(MySearchView, self).get_queryset()
        # further filter queryset based on some set of criteria
        return queryset.filter(pub_date__gte=date(2015, 1, 1))

    def get_context_data(self, *args, **kwargs):
        context = super(MySearchView, self).get_context_data(*args, **kwargs)
        # do something
        return context

# urls.py

urlpatterns = [
    url(r'^/search/?$', MySearchView.as_view(), name='search_view'),
]

首先要清楚context里面都有什么(翻代码)

'''
检索出来的内容都在object_list
context['object_list']
'''
context = {
                'paginator': paginator,
                'page_obj': page,
                'is_paginated': is_paginated,
                'object_list': queryset
            }

 输出检索内容的相关国家

# models.py 不完善
class Country(models.Model):
    name = models.CharField(max_length=128, verbose_name='国家', null=True)
    slug = models.SlugField(unique=True, help_text='与该条数据的id值相同即可')

    class Meta:
        verbose_name = '国家'
        verbose_name_plural = '国家列表'

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse('blog:country', kwargs={'slug': self.slug})

    def get_article_list(self):
        '''返回当前标签下所有发表的文章列表'''
        return Article.objects.filter(country=self)

class Article(models.Model):
    author = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name='上传人员', on_delete=models.PROTECT)
    title = models.CharField(max_length=150, verbose_name='文章标题')
    country = models.ForeignKey(Country, verbose_name='国家', on_delete=models.PROTECT, null=True)


# views.py
# 重写搜索视图,可以增加一些额外的参数,且可以重新定义名称
class MySearchView(SearchView):
    context_object_name = 'search_list'
    paginate_by = getattr(settings, 'BASE_PAGE_BY', None)
    paginate_orphans = getattr(settings, 'BASE_ORPHANS', 0)
    queryset = SearchQuerySet().order_by('-views')

    def get_context_data(self, *args, **kwargs):
        context = super(MySearchView, self).get_context_data(*args, **kwargs)
        # do something

        for i in context['object_list']:
            print(i.object.country)

        return context


# urls.py
path('search/', MySearchView.as_view(), name='search_view'),  # 全文搜索

 

相关标签: 项目开发