Django:按月计数对象 [英] Django: Count objects by month
问题描述
我研究了Django文档,并尝试了许多示例,但是它实际上并不容易,尽管实际上应该很简单.
I studied the Django docu and tried many examples but it still doesn't work, though it should be very easy, actually.
这是我的模特
class Dummy(models.Model):
timestamp = models.DateTimeField()
我有一些示例对象,可以像这样通过外壳列出:
I have some sample objects which I am able to list via the shell like that:
% python manage.py shell
Python 3.7.7 (default, Mar 10 2020, 15:43:33)
[Clang 11.0.0 (clang-1100.0.33.17)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from conv.models import Dummy
>>> dummy = Dummy.objects.order_by('timestamp')
>>> for d in dummy:
... print(d.id, d.timestamp)
6 2019-05-01 07:00:06+00:00
4 2020-04-01 22:00:00+00:00
5 2020-04-15 04:00:00+00:00
1 2020-05-17 09:42:00+00:00
2 2020-05-18 09:42:15+00:00
3 2020-05-19 09:42:21+00:00
>>>
现在,我想按年/月计数对象.仅按年份过滤:
Now I want to count the objects by year / month. Filtering by year only works:
>>> Dummy.objects.filter(timestamp__year='2020').count()
5
但是按月过滤不起作用:
But filtering by month doesn't work:
>>> Dummy.objects.filter(timestamp__month='5').count()
0
实际上结果应该是4.怎么了?
Actually the result should be 4. What's wrong?
推荐答案
There was some trouble with the MySQL-DB I was using very similar to this topic. When I switched back to SQLite I got the correct result:
>>> Dummy.objects.filter(timestamp__month='5').count()
4
现在,我还可以像这样将年份和月份的过滤组合在一起:
Now I also can combine filtering for year and month like that:
>>> Dummy.objects.filter(timestamp__year='2020', timestamp__month='5').count()
3
感谢 Willem Van Onsem的慷慨帮助我现在看到的事情更加清楚了,并且了解了很多有关TruncMonth和ExtractMonth的知识.似乎也是非常有用的工具.
Thanks to the generous help of Willem Van Onsem I see things clearer now and learned a lot about TruncMonth and ExtractMonth which seems to be very useful tools too.
这篇关于Django:按月计数对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!