Annotate (group) dates by month/year in Django

后端 未结 2 1505
心在旅途
心在旅途 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:36

    Try something along these lines:

    from django.db.models import Count
    
    Item.objects.all().\
            extra(select={'year': "EXTRACT(year FROM date)"}).\
            values('year').\
            annotate(count_items=Count('date'))
    

    You might want to use item_instance._meta.fields instead of manually specifying "date" in the MySQL statement there...

    Also, note that I started with Item QuerySet instead of Group, for the sake of simplicity. It should be possible to either filter the Item QuerySet to get the desired result, or to make the extra bit of MySQL more complicated.

    EDIT:

    This might work, but I'd definitely test the guts out of it before relying on it :)

    Group.objects.all().\
        values('item__date').\
        extra(select={'year': "EXTRACT(year FROM date)"}).\
        values('year').\
        annotate(count=Count('item__date'))
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题