Django - 计算模型实例视图(对于“顶级条目"应用程序) [英] Django - counting model instance views (for a "top entries" app)

查看:22
本文介绍了Django - 计算模型实例视图(对于“顶级条目"应用程序)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新手,很困惑.我想创建一个模块来跟踪文章和博客模型的热门"实例.我不想触及文章或博客模型的代码.这是中间件的候选者吗?查看 HttpRequest.path?

I'm new, and confused. I want to create a module that keeps track of the "top hit" instances of both an article and a blog model. I don't want to touch the code for the article or blog models. Is this a candidate for middleware? looking at the HttpRequest.path?

推荐答案

查看 request.path 的中间件很丑陋,因为它引入了对用于显示文章和博客文章的 URL 模式细节的依赖.如果您不介意这种耦合,那么您不妨保存性能损失并在网络服务器日志文件上进行分析.(编辑:查看中间件 将是一个更好的选择,因为它为您提供了可调用的视图及其参数.我仍然更喜欢装饰器方法,因为它不会对不相关的视图产生开销,但是如果您不想接触 URLconf,则视图中间件可以工作用于博客/文章应用程序).

Middleware looking at request.path is ugly, as it introduces a dependency on the details of the URL patterns you use to display articles and blog posts. If you don't mind this coupling, then you might as well just save the performance hit and do your analysis on webserver log files. (EDIT: view middleware would be a better option, as it gives you the view callable and its args. I'd still prefer the decorator approach as it incurs no overhead on unrelated views, but view middleware would work if you don't want to touch the URLconf for the blog/article applications).

我会使用一个视图装饰器,您可以将其环绕在 object_detail 视图(或您的自定义等效项)周围.您可以直接在 URLconf 中进行此包装.像这样:

I'd use a view decorator that you wrap around the object_detail view (or your custom equivalent). You can do this wrapping directly in the URLconf. Something like this:

def count_hits(func):
    def decorated(request, *args, **kwargs):
        # ... find object and update hit count for it...
        return func(request, *args, **kwargs)
    return decorated

你可以在views.py中应用它:

And you can apply it in views.py:

@count_hits
def detail_view(...

或在您的 URLconf 中:

or in your URLconf:

url(r'^/blog/post...', count_hits(detail_view))

这篇关于Django - 计算模型实例视图(对于“顶级条目"应用程序)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆