Annotate (group) dates by month/year in Django

后端 未结 2 1504
心在旅途
心在旅途 2020-12-31 13:13

Using the Django DateQuerySet I\'m pulling related years for item objects from a Group query.

>>> Group.objec         


        
2条回答
  •  孤城傲影
    2020-12-31 13:41

    For anyone finding this after django 1.9 there is now a TruncDate (TruncMonth, TruncYear) that will do this.

    from django.db.models.functions import TruncDate
    
    (Group.objects.all().annotate(date=TruncDate('your_date_attr')
                        .values('date')
                        .annotate(Count('items'))
    

    Hope it helps.

提交回复
热议问题