【问题标题】:Django querying top weekly hits in a DatabaseDjango 查询数据库中的每周最高点击量
【发布时间】:2016-06-05 20:45:54
【问题描述】:

我目前正在使用 django 的 ORM 函数为我的 Web 应用程序构建一个可行的后端。我的models.py 中有一个Model 对象,它与特定的url 相关并显示在特定的url 中,该url 使用https://github.com/thornomad/django-hitcount 跟踪命中。我想通过显示以下图表来更好地组织我的 Web 应用程序(今天的顶级“模特”,本周的顶级“模特”,本月的顶级“模特”,今年的顶级“模特”,所有时间的顶级“模特”) 目前我的代码设置是这样的,试图在本周获得顶级“模型”,因为我在 'django-hitcount' 文档中没有看到任何更好的方法来做到这一点

modelList = MyModel.objects.all()



for model in modelList
    model.hit_count.hits_in_last(days=7)
 '''
 then somehow compare this models weekly hits 
 to all the other models weekly hits organized by the top 100
 i'd like to add the top 100 weekly models to a new list then render it '''

代码 cmets 本质上是我的问题。我对python或Django一点也不流利,Java是我的主要语言,如果这个问题听起来很愚蠢,请原谅我

【问题讨论】:

  • 如果不了解 hitcount 模块,这将很难回答,但您希望根据最新的命中进行注释,然后按此排序。即annotate(latest_hits=Q('latest_hits_querything')).orderby('latest_hits')[:100]
  • 由于这个问题有点特定于这个包,你可能会在 GitHub 项目问题跟踪器上提出这个问题。看起来 django-hitcount 正在积极开发中。

标签: python django web-applications


【解决方案1】:

从未使用过这个包,但在检查了models definition 之后,他们使用GFK 来存储任何模型或您的模型的命中数,因此为了过滤/注释他们的模型,您可以定义自己的reverse relation

from django.contrib.contenttypes.fields import GenericRelation

class MyModel(models.Model):
    # ..

    hitcounts = GenericRelation(
        HitCount,
        content_type_field='content_type',
        object_id_field='object_pk',
    )

现在尝试使用此查询集获取您在一段时间内访问次数最多的模型:

period = timezone.now() - timedelta(days=7)
top_models = MyModel.objects.filter(
        hitcounts__hit__created__gte=period
    ).annotate(
        counts=models.Count('hitcounts__hit')
    ).order_by('-counts')

【讨论】:

    猜你喜欢
    • 2013-01-23
    • 2021-01-06
    • 1970-01-01
    • 2012-04-27
    • 1970-01-01
    • 2013-04-16
    • 1970-01-01
    • 2014-06-17
    • 2018-03-03
    相关资源
    最近更新 更多