Nov 10, 2011

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, 1),
                                date__lte=datetime.date(2011, 1, 31)

samples = Sample.objects.filter(date__gt=datetime.date(2011, 1, 1),
                                date__lt=datetime.date(2011, 1, 31)


Django queryset filters is quite interesting things to discover. They also can cover almost any simple database query. In this example we are filtering model objects that are between dates range. This filters go through model's date fields and look for items in this date range. Only difference here that firs example includes 1-31 days and second includes 2-30 days range (excluding specified days).

  • '__gte' means '>='
  • '__lte' means '<='
  • '__gt' means '>'
  • '__lt' means '<'
Easy to remember right?
Found interesting, Helped,  Know a better way, I'm not right somewhere. Please drop me a comment below. 



No comments:

Post a Comment