django mariadb filter month 失败

django框架中,用查询语句查询mariadb数据库,过滤一年中每个月的数据,查询结果为空

代码:

#字段
class User(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)

#查询语句
     i = 1:
     while i <= 12:

         all_datas = User.objects.filter(created_at__month=i)
         i += 1

  

代码不是全部代码,主要是循环查询12个月的数据,之前用的数据库是mysql,数据查询是没有问题的。结果换了mariadb(实际上两者区别不是很大),结果查询时空

查询月数据失败

查找原因发现挺多人遇到过这个问题,包括在mysql上都有人遇到,看来我还是幸运的

解决方案:

all_datas = User.objects

        user_num_per_mounth = {}
        i = 1
        while i <= 11:
            cur_month = timezone.datetime(cur_year, i, 1)
            next_month = timezone.datetime(cur_year, i+1, 1)
            new_users_num = all_datas.filter(created_at__gte=cur_month, created_at__lt=next_month)
            user_num_per_mounth[i] = new_users_num.count()
            i += 1

  

12月的数据另查就行了,是下一年的一月之前和本年12月1日之后。

cur_month = timezone.datetime(cur_year, i, 1)
#括号里的是规定的格式了(year,month,day)

  

 

posted @ 2018-01-21 11:16  django_start  阅读(197)  评论(0编辑  收藏  举报