我研究了 Django 文档并尝试了很多示例,但它仍然不起作用,尽管实际上它应该非常简单。
这是我的模型:
class Dummy(models.Model):
timestamp = models.DateTimeField()
我有一些示例对象,我可以通过 shell 列出这些对象,如下所示:
% 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
>>>
现在我想按年/月对对象进行计数。仅按年份过滤有效:
>>> Dummy.objects.filter(timestamp__year='2020').count()
5
但是按月份过滤不起作用:
>>> Dummy.objects.filter(timestamp__month='5').count()
0
实际上结果应该是4。出了什么问题?
最佳答案
我使用的 MySQL-DB 出现了一些问题,与 this topic 非常相似。 。当我切换回 SQLite 时,我得到了正确的结果:
>>> Dummy.objects.filter(timestamp__month='5').count()
4
现在我还可以像这样组合过滤年份和月份:
>>> Dummy.objects.filter(timestamp__year='2020', timestamp__month='5').count()
3
感谢generous help of Willem Van Onsem我现在看得更清楚了,并且学到了很多关于 TruncMonth 和 ExtractMonth 的知识,它们似乎也是非常有用的工具。
关于Django:按月计数对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61888487/