如何将pk从视图传递到cache_page装饰器中的key_prefix函数

时间:2019-06-20 11:36:27

标签: django django-views django-cache

是否有可能使用装饰器/函数关系将“ pk”从视图“ show_by_heading_view”传递给函数“ variant_on_paginated_or_not”? 我唯一想到的方法就是分析请求并从那里获取请求:

pk = request.get_full_path_info().split("/")[-2]

但这是一种不可靠的方法,因为url可能会被更改。我更喜欢用pythonic的方式来做,但是不知道怎么做。

fancy_cache包中的

@cache_page装饰器,因此它可以使用可调用的…

函数“ variate_on_paginated_or_not”指定是否涉及分页,如果不这样做,则使缓存无效...

谢谢

def vary_on_paginated_or_not(request):
    pk = request.get_full_path_info().split("/")[-2]
    count_eq = Article.objects.filter(foreignkey_to_subheading=int(pk)).count()
    return "show_by_heading_view+%s" % True if count_eq > 10 else False


@cache_page(60*60*24*7, key_prefix=vary_on_paginated_or_not)
def show_by_heading_view(request, pk): #597
    current_heading = get_object_or_404(SubHeading, pk=pk)
    list_of_articles = Article.objects.filter(foreignkey_to_subheading=pk)
    if "keyword" in request.GET:
        keyword = request.GET["keyword"]
        keyword_unidecode = unidecode.unidecode(keyword)
        q = Q(title__icontains=keyword) | Q(content__icontains=keyword) | Q(
            title__icontains=keyword_unidecode) | Q(content__icontains=keyword_unidecode)
        list_of_articles = list_of_articles.filter(q)
    else:
        keyword = ""
    form = SearchForm(initial={"keyword": keyword})
    paginator = Paginator(list_of_articles, 10)
    if "page" in request.GET:
        page_num = request.GET["page"]
    else:
        page_num = 1
    page = paginator.get_page(page_num)
    context = {"current_heading": current_heading, "page": page,
               "list_of_articles": page.object_list, "form": form}  # 597
    return render(request, "articles/show_by_subheading.html", context)

0 个答案:

没有答案
相关问题