Skip to main content
 首页 » 编程设计

python之Django 查询数据库中的每周最高命中率

2024年08月22日24mayingbao

我目前正在使用 Django 的 ORM 函数为我的 Web 应用程序构建一个可行的后端。我的 models.py 中有一个模型对象,它与一个特定的 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 ''' 

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

请您参考如下方法:

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