美文网首页
django 按时间筛选,今年,去年,上月

django 按时间筛选,今年,去年,上月

作者: 青穗黄 | 来源:发表于2018-03-09 12:03 被阅读213次

    today = datetime.datetime.now()
    1 Current year

    Order.objects.filter(created_at__year=today.year)
    2 Current month

    Order.objects.filter(created_at__year=today.year, created_at__month=today.month)
    3 Last month

    last_month = today.month - 1 if today.month>1 else 12
    last_month_year = today.year if today.month > last_month else today.year - 1

    Order.objects.filter(created_at__year=last_month_year, created_at__month=last_month)
    4 Last year

    last_year = today.year - 1
    Order.objects.filter(created_at__year=last_year)
    5 Single Query

    As last year + current year includes last month and current month, and all orders>= last_year includes current year, the query is super simple:

    Order.objects.filter(created_at__year__gte=last_year)

    from:[https://stackoverflow.com/questions/28101480/how-can-i-query-for-objects-in-current-year-current-month-in-django]

    相关文章

      网友评论

          本文标题:django 按时间筛选,今年,去年,上月

          本文链接:https://www.haomeiwen.com/subject/yxypfftx.html