开发者

Django queryset dates: aggregate and format months as name strings

开发者 https://www.devze.com 2023-01-22 19:15 出处:网络
I\'ve got a simple blog application which I\'m porting to Django. One stumbling block I\'ve come across is the aggregation of article entries by month, and displaying that as a list. Each article in t

I've got a simple blog application which I'm porting to Django. One stumbling block I've come across is the aggregation of article entries by month, and displaying that as a list. Each article in the db has a simple datetime field. The HTML output should be something like:

2010

  • January (3 entries)
  • February (2 entries)
  • March (3 entries)

etc.

I'm currently using a {% foreach %} block in the template to lo开发者_C百科op through all the months returned from the query.

Going with dates('datestamp','month') seems to be the right direction, but how do I get article counts in the results, and how would I format the month integers to be name strings in the template?


You can use django-cube for this. With the following code in your views.py (and then connect entry_count in your urls), you should get what you need :

# cube declaration
from cube.models import Cube, Dimension

class EntryCube(Cube):

    #replace <your_date_field> by the field name
    month = Dimension('<your_date_field>__month') 
    year = Dimension('<your_date_field>__year')

    @staticmethod
    def aggregation(queryset):
        return queryset.count()

# views declaration
from .models import <YourModel> #replace by your model
from cube.views import table_from_cube

def entry_count(request):
    cube = EntryCube(<YourModel>.objects.all())
    return table_from_cube(request, cube, ['year', 'month'], template='table.html')
    #template 'table.html' is in 'example/template' folder, copy it in your template folder, and modify it to your wish.

EDIT :

If you want to customize the way dimensions are displayed, you can just subclass Dimension (see this snippet):

class MonthDimension(Dimension):

    @property
    def pretty_constraint(self):
        #just return the month name according to the month number that you can get in "self.constraint", e.g. self.constraint = 1 -> return 'january'
        return month_name

(I plan to provide subclasses of dimensions to allow different formats like what you need. So if you do use django-cube, and write a good subclass of Dimension to format dates, I would be happy to take a look at it !)


Ok ... it is overkill for what you want. However, if you decide after that you want more statistics on your entries (for example number of entries/author/month/year/tag, etc ...), you simply add a dimension to the cube. If you decide to use this, and need more help, please ask !

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号