首页 > 解决方案 > Django TruncWeek 中的错误返回

问题描述

TruncDate 和 TruncMonth 返回正确的数据,但是当使用 TruncWeek 时,数据不会像我使用 TruncMonth/Date 那样返回

使用 TruncDate 和 TruncMonth 的两个函数模型运行良好,并且 TruncWeek 必须运行

class TblogByDateSerializer(serializers.ModelSerializer): groupby = serializers.CharField() total = serializers.IntegerField() class Meta: model = Tblog fields = ('groupby','total')

查询集:

Tblog.objects.filter(status='success').annotate(groupby=TruncMonth('createtime',output_field=DateField())).values('groupby').annotate(total=Count('createtime')).order_by('-groupby')[:7]

如果我将TruncMonth函数更改TruncWeek为代码应该按周分组,

当我使用使用 TruncMonth使用 TruncDate时的结果这是使用 TruncWeek时的问题

使用 TruncMonth 和 TruncDate 时的结果,TruncWeek 也应该像这样返回,


"results": [
    {
        "groupby": "2019-08-01",
        "total": 77
    },
    {
        "groupby": "2019-07-01",
        "total": 24
    }
"results": [
    {
        "groupby": "2019-08-06",
        "total": 29
    },
    {
        "groupby": "2019-08-05",
        "total": 6
    },
    {
        "groupby": "2019-08-04",
        "total": 4
    },
    {
        "groupby": "2019-08-03",
        "total": 4
    },
    {

使用 TruncWeek 时


"results": [
    {
        "groupby": "2019-08-05",
        "total": 1
    },
    {
        "groupby": "2019-08-05",
        "total": 1
    },
    {
        "groupby": "2019-08-05",
        "total": 1
    },
    {
        "groupby": "2019-08-05",
        "total": 1
    },
    {
        "groupby": "2019-08-05",
        "total": 1
    },
    {
        "groupby": "2019-08-05",
        "total": 1
    },
    {
        "groupby": "2019-08-05",
        "total": 1
    }

标签: pythondjangodjango-rest-framework

解决方案


我改变了TruncWeek('createtime',output_field=DateField()).TruncWeek('createtime'),它对我有用,

我认为问题在于使用groupby = serializers.CharField()outpufield using DateField


推荐阅读