我有这样一个注释:它显示字段的月份计数

bar = Foo.objects.annotate(
    item_count=Count('item')
).order_by('-item_month', '-item_year')

这会产生如下输出:

我想展示每个月(第一个月除外)与上个月的项目数量相比,项目数量的变化.我如何使用注释实现这一点,或者我需要使用Pandas ?

谢谢

编辑:

SELECT item_month, item_year, COUNT(item),
LAG(COUNT(item)) OVER (ORDER BY item_month, item_year)
FROM Foo 
GROUP BY item_month, item_year

(备注:item_month和item_year是日期字段)

Django ORM在SQL中有类似的延迟吗?

推荐答案

对于这些类型的查询,需要在django Orm中使用窗口函数

对于滞后,你可以求助于

https://docs.djangoproject.com/en/4.0/ref/models/database-functions/#lag

Orm中的工作查询如下所示:

#模特.py

class Review(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='review_user', db_index=True)
    review_text = models.TextField(max_length=5000)
    rating = models.SmallIntegerField(
        validators=[
            MaxValueValidator(10),
            MinValueValidator(1),
        ],
    )
    date_added = models.DateTimeField(db_index=True)
    review_id = models.AutoField(primary_key=True, db_index=True)

这只是一个虚拟表,向您展示django中LagWindow函数的用例

from django.db.models.functions import Lag, ExtractYear
from django.db.models import F, Window

print(Review.objects.filter().annotate(
        num_likes=Count('likereview_review')
    ).annotate(item_count_lag=Window(expression=Lag(expression=F('num_likes')),order_by=ExtractYear('date_added').asc())).order_by('-num_likes').distinct().query)

查询将看起来像

SELECT DISTINCT `temp_view_review`.`user_id`, `temp_view_review`.`review_text`, `temp_view_review`.`rating`, `temp_view_review`.`date_added`, `temp_view_review`.`review_id`, COUNT(`temp_view_likereview`.`id`) AS `num_likes`, LAG(COUNT(`temp_view_likereview`.`id`), 1) OVER (ORDER BY EXTRACT(YEAR FROM `temp_view_review`.`date_added`) ASC) AS `item_count_lag` FROM `temp_view_review` LEFT OUTER JOIN `temp_view_likereview` ON (`temp_view_review`.`review_id` = `temp_view_likereview`.`review_id`) GROUP BY `temp_view_review`.`review_id` ORDER BY `num_likes` DESC

此外,如果您不想在提取的日期年订购,那么可以使用F个这样的表达式

print(Review.objects.filter().annotate(
        num_likes=Count('likereview_review')
    ).annotate(item_count_lag=Window(expression=Lag(expression=F('num_likes')),order_by=[F('date_added')])).order_by('-num_likes').distinct().query)

对此的查询:

SELECT DISTINCT `temp_view_review`.`user_id`, `temp_view_review`.`review_text`, `temp_view_review`.`rating`, `temp_view_review`.`date_added`, `temp_view_review`.`review_id`, COUNT(`temp_view_likereview`.`id`) AS `num_likes`, LAG(COUNT(`temp_view_likereview`.`id`), 1) OVER (ORDER BY `temp_view_review`.`date_added`) AS `item_count_lag` FROM `temp_view_review` LEFT OUTER JOIN `temp_view_likereview` ON (`temp_view_review`.`review_id` = `temp_view_likereview`.`review_id`) GROUP BY `temp_view_review`.`review_id` ORDER BY `num_likes` DESC

Python相关问答推荐

用Python解密Java加密文件

如何在Django基于类的视图中有效地使用UTE和RST HTIP方法?

如何将Docker内部运行的mariadb与主机上Docker外部运行的Python脚本连接起来

Julia CSV for Python中的等效性Pandas index_col参数

ODE集成中如何终止solve_ivp的无限运行

无法使用DBFS File API路径附加到CSV In Datricks(OSError Errno 95操作不支持)

Pre—Commit MyPy无法禁用非错误消息

我如何根据前一个连续数字改变一串数字?

为一个组的每个子组绘制,

如何在Python中找到线性依赖mod 2

mypy无法推断类型参数.List和Iterable的区别

CommandeError:模块numba没有属性generated_jit''''

LocaleError:模块keras._' tf_keras. keras没有属性__internal_'''

Cython无法识别Numpy类型

根据客户端是否正在传输响应来更改基于Flask的API的行为

为什么dict. items()可以快速查找?

如何根据一定条件生成段id

FileNotFoundError:[WinError 2]系统找不到指定的文件:在os.listdir中查找扩展名

如何使用count()获取特定日期之间的项目

使代码更快地解决哪个字母代表给定公式中的哪个数字