Django查询数据库中每周排名前列的热门记录

2024-05-13 04:08:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在使用django的ORM函数为我的web应用程序构建一个可行的后端。我在我的模型.py它与使用https://github.com/thornomad/django-hitcount跟踪点击的特定url相关并显示在该url中。我想通过显示以下图表来更好地组织我的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 '''

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


Tags: thetodjango代码模型web应用程序url
1条回答
网友
1楼 · 发布于 2024-05-13 04:08:14

从来没有使用过这个包,但是在检查了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',
    )

现在尝试使用以下查询集获取某段时间内访问量最大的模型:

^{pr2}$

相关问题 更多 >