首页 \ 问答 \ Django按月和年查询组(Django query group by month and year)

Django按月和年查询组(Django query group by month and year)

我有一个像这样的Django模型:

class EVENT(models.Model):
    user = models.CharField(max_length=255)
    pay_time = models.DateTimeField(default=timezone.now)

我需要计算每个月对某一组用户的平均记录数。 我在列表中有用户名,我希望按月和年分组,以便在平均计算中使用。 我的查询是这样的:

from django.db import models
from django.db.models import Func, F, Count
class Month(Func):
    function = 'EXTRACT'
    template = '%(function)s(MONTH from %(expressions)s)'
    output_field = models.IntegerField()

class Year(Func):
    function = 'EXTRACT'
    template = '%(function)s(YEAR from %(expressions)s)'
    output_field = models.IntegerField()

#ru is the list of usernames I want to get the average per month for
trx = EVENT.objects.filter(user__in=ru).annotate(m=Month('pay_time'), y=Year('pay_time')).values('m', 'y').annotate(c=Count('id'))

当我运行此查询时,我得到了我认为我想要的结果。 这是我得到的样本:

<QuerySet [{'y': 2016, 'c': 61098, 'm': 4}, {'y': 2016, 'c': 104632, 'm': 5}]>

我想确保这样运行此查询:

trx2 = EVENT.objects.filter(user__in=ru, pay_time__year=2016, pay_time__month=4) 

我得到了60990条记录的结果。
这意味着我从第一个查询得到的结果是不正确的。 我知道我可以在循环中使用第二个查询来获得我想要的但是与使用GROUP BY运行一个查询相比,这将非常慢。

谢谢,

编辑:
这是print trx.query的输出:

SELECT 
    EXTRACT(YEAR from `events_event`.`pay_time`) AS `y`,  
    EXTRACT(MONTH from `events_event`.`pay_time`) AS `m`,
    COUNT(`events_event`.`id`) AS `c`
FROM `events_event`
WHERE  
 `events_event`.`user` IN ('user1', 'user2')
GROUP BY 
  EXTRACT(YEAR from `events_event`.`pay_time`),
  EXTRACT(MONTH from `events_event`.`pay_time`)  
ORDER BY NULL  

这是print trx2.query的输出:

SELECT
    `events_event`.`id`,
    `events_event`.`user`,
    `events_event`.`pay_time`,
FROM `events_event`
WHERE
    (`events_event`.`user` IN ('user1', 'user2')
 AND `events_event`.`pay_time` BETWEEN 2015-12-31 22:00:00 AND 2016-12-31 21:59:59.999999 
 AND EXTRACT(MONTH FROM CONVERT_TZ(`events_event`.`pay_time`, 'UTC', Africa/Cairo)) = 4)  

I have a Django model like this:

class EVENT(models.Model):
    user = models.CharField(max_length=255)
    pay_time = models.DateTimeField(default=timezone.now)

I need to calculate the average number of records per month I have for a certain group of users. I have the user names in a list and I want to group by month and year to use in the average calculation. My query is like this:

from django.db import models
from django.db.models import Func, F, Count
class Month(Func):
    function = 'EXTRACT'
    template = '%(function)s(MONTH from %(expressions)s)'
    output_field = models.IntegerField()

class Year(Func):
    function = 'EXTRACT'
    template = '%(function)s(YEAR from %(expressions)s)'
    output_field = models.IntegerField()

#ru is the list of usernames I want to get the average per month for
trx = EVENT.objects.filter(user__in=ru).annotate(m=Month('pay_time'), y=Year('pay_time')).values('m', 'y').annotate(c=Count('id'))

When I run this query I get the results I thought I wanted. That's a sample of what I got:

<QuerySet [{'y': 2016, 'c': 61098, 'm': 4}, {'y': 2016, 'c': 104632, 'm': 5}]>

I wanted to make sure so I ran this query:

trx2 = EVENT.objects.filter(user__in=ru, pay_time__year=2016, pay_time__month=4) 

And I got the result 60990 records.
This means that the results I got from the first query are incorrect. I know I can use the second query in a loop to get what I want but this will be very slow compared to running one query using GROUP BY.

Thanks,

EDIT:
Here is the output of print trx.query:

SELECT 
    EXTRACT(YEAR from `events_event`.`pay_time`) AS `y`,  
    EXTRACT(MONTH from `events_event`.`pay_time`) AS `m`,
    COUNT(`events_event`.`id`) AS `c`
FROM `events_event`
WHERE  
 `events_event`.`user` IN ('user1', 'user2')
GROUP BY 
  EXTRACT(YEAR from `events_event`.`pay_time`),
  EXTRACT(MONTH from `events_event`.`pay_time`)  
ORDER BY NULL  

And this is the output of print trx2.query:

SELECT
    `events_event`.`id`,
    `events_event`.`user`,
    `events_event`.`pay_time`,
FROM `events_event`
WHERE
    (`events_event`.`user` IN ('user1', 'user2')
 AND `events_event`.`pay_time` BETWEEN 2015-12-31 22:00:00 AND 2016-12-31 21:59:59.999999 
 AND EXTRACT(MONTH FROM CONVERT_TZ(`events_event`.`pay_time`, 'UTC', Africa/Cairo)) = 4)  

原文:https://stackoverflow.com/questions/46140771
更新时间:2023-01-22 15:01

最满意答案

没有优雅的方法(至少有一个我知道的)。 许多Ansible模块需要在执行任务的主机上安装额外的软件包。 在第一次执行游戏或任务时遇到这些问题是很常见的。

所以我想最优雅的方法是为Galaxy角色创建一个pull请求,通过额外的任务将这些依赖项添加到游戏中。


There is no elegant way of doing that (at least one that I'm aware of). Many Ansible modules require extra packages to be installed on the host that executes the task. It's common to hit those problems when first executing a play or task.

So I guess the most elegant way would be to create a pull request for the Galaxy role to add those dependencies to the play with an extra task.

相关问答

更多
  • 事实证明我缺少一些关键依赖项: build-essential , libxslt1-dev , libxml2-dev和zlib1g-dev 。 我在这里发现了这个评论: https : //github.com/mitchellh/vagrant-aws/issues/163#issuecomment-27603855非常有帮助。 It turns out I was missing some key dependencies: build-essential, libxslt1-dev, libxml ...
  • 如果您不想仅为当前用户安装,请使用user_install: false 。 默认情况下是这样的: 在用户的本地gems缓存或所有用户中安装gem Use user_install: false if you don't want to install only for the current user. By default it's true: Install gem in user's local gems cache or for all users
  • 没有优雅的方法(至少有一个我知道的)。 许多Ansible模块需要在执行任务的主机上安装额外的软件包。 在第一次执行游戏或任务时遇到这些问题是很常见的。 所以我想最优雅的方法是为Galaxy角色创建一个pull请求,通过额外的任务将这些依赖项添加到游戏中。 There is no elegant way of doing that (at least one that I'm aware of). Many Ansible modules require extra packages to be insta ...
  • 我知道我不是一个专家,但如果一些新手有同样的问题,也许这可以帮助。 正如我几天前写的,你正在学习可靠的,你有很多服务器,你甚至可以在几分钟内将nginx,php-fpm,mysql等安装在一个非常新的ubuntu / centos中。 我在说什么? 不是一个,而是服务器在同一时间,这个梦想。 但哦,哦,现在你必须在lemp服务器1和lemp服务器2中安装不同的cron任务。 然后,你必须玩弄可靠的变量。 当你是新手时,变量可能会有点棘手。 我并不是说这是更好的方法,但至少,您不必为每台服务器维护单独的cro ...
  • 在定义Web服务器本身时,您可以提供ssh和sudo密码 [group1] ansible_host=10.40.0.168 ansible_ssh_user=user1 ansible_ssh_pass=***** ansible_sudo_pass=***** [group2] ansible_host=10.40.0.83 ansible_ssh_user=user2 ansible_ssh_pass=***** ansible_sudo_pass=***** 参考 You can give th ...
  • 是的,你必须先安装Homebrew。 homebrew Ansible模块文档不清楚; 如果你检查它的源代码 ,如果它找不到Homebrew它就会失败并且它不会尝试为你安装它。 已经有关于如何在Homebrew的安装脚本中绕过提示的答案。 还有其他方法可以安装Homebrew,例如将其作为tarball下载并将其解tar到某个地方(可以使用unarchive Ansible模块执行 )或使用git克隆其源代码。 Yes, you have to install Homebrew first. The hom ...
  • 尝试执行ansible-playbook -vv ,它为每个执行的任务显示“任务路径”,如下所示: TASK [debug] ********************************************* task path: /path/to/task/file.yml:5 ok: [localhost] => { "msg": "aaa" } 因此,您可以轻松跟踪实际文件(包括或不包含)路径和行号。 至于includes ,在当前的Ansible版本(2.2,2.3)中有不同类型的 ...
  • 语法不正确。 您应该使用YAML或JSON来定义列表,但不能同时使用两者。 dependencies: - ~/Ansible/Roles/ROLE_A 但是,如果roles位于roles目录中,则无需提供角色的完整路径。 所以以下内容应该足够了: dependencies: - ROLE_A The syntax is incorrect. Either you should use YAML or JSON to define a list, but not both. dependenci ...
  • 您可以向变量注册apt模块执行的输出,然后将其打印出来。 - hosts: localhost sudo: true tasks: - name: get vi apt: state=latest name=vim register: aptout # show the content of aptout var - debug: var=aptout You can register to a variable the output of the ...
  • 您的解决方案有两个问题。 第一个是,默认情况下, shell命令使用非交互式非登录shell,因此它将完全跳过运行/etc/profile.d/dart.sh ,从而添加PATH 。 但是,如果您使用登录shell,它将正常工作,因为登录shell读取/etc/profile.d : - hosts: all tasks: - name: install stagehand shell: bash -lc "pub global activate stagehand" 第二个问题是 ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)