Annotate (group) dates by month/year in Django

后端 未结 2 1506
心在旅途
心在旅途 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'))
    

提交回复
热议问题