Skip to main content

Posts

Showing posts with the label query

Django: Adding news archive. Querying models with date and time filtering.

Today I had some practice with filtering Django models by date. Task was to archive old entries of the news. I've made 2 separate views for those. I was displaying actually news and another was ment to display archived items. Quite common task I guess. Also those 2 views are under wired buggy CMS, but we are not talking about that now. Will save some examples for future of mine/someones usage. Time. Subtracting a year from today with Python dateutil : from datetime import date , timedelta d = date . today ( ) - timedelta ( days = days_to_subtract ) This example returns 'd' that has less days than specified in 'days_to_subtract' . timedelta function also can be fed with 'months' , 'years' and so on. Becomes handy during time calculations. If you change this minus into plus you can calculate future time. Filtering Querysets. Filtering by date ranges. samples = Sample . objects . filter ( date__gte = datetime . date ( 2011 , 1...