Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Filtering datetime field by *only* the year value?

Tags:

I'm trying to spit out a django page which lists all entries by the year they were created. So, for example:

2010:

  • Note 4

  • Note 5

  • Note 6

2009:

  • Note 1

  • Note 2

  • Note 3

It's proving more difficult than I would have expected. The model from which the data comes is below:

class Note(models.Model):     business = models.ForeignKey(Business)     note = models.TextField()     created = models.DateTimeField(auto_now_add=True)     updated = models.DateTimeField(auto_now=True)     class Meta:         db_table = 'client_note'      @property     def note_year(self):         return self.created.strftime('%Y')      def __unicode__(self):         return '%s' % self.note 

I've tried a few different ways, but seem to run into hurdles down every path. I'm guessing an effective 'group by' method would do the trick (PostGres DB Backend), but I can't seem to find any Django functionality that supports it. I tried getting individual years from the database but I struggled to find a way of filtering datetime fields by just the year value. Finally, I tried adding the note_year @property but because it's derived, I can't filter those values.

Any suggestions for an elegant way to do this? I figure it should be pretty straightforward, but I'm having a heckuva time with it. Any ideas much appreciated.

like image 848
PlankTon Avatar asked Jun 08 '10 12:06

PlankTon


People also ask

How can I filter a Django query with a list of values?

The sql query will be like SELECT * FROM mytable WHERE ids=[1, 3, 6, 7, 9] which is not true. You have to use in operator for this so you query will be like SELECT * FROM mytable WHERE ids in (1, 3, 6, 7, 9) for that Django provide __in operator.

How can I filter a date of a DateTimeField in Django?

To filter a date of a DateTimeField in Python Django, we can use filter with a datetime. to call filter to return the results with the datetime_published field set to 2018-03-27.

How do I filter records in Django?

The filter() method is used to filter you search, and allows you to return only the rows that matches the search term.

Can you filter by property Django?

Nope. Django filters operate at the database level, generating SQL. To filter based on Python properties, you have to load the object into Python to evaluate the property--and at that point, you've already done all the work to load it.


1 Answers

Either construct custom SQL or use

date_list = Note.objects.all().dates('created', 'year')  for years in date_list:     Note.objects.filter(created__year = years.year) 

This is the way it is done in date based generic views.

like image 180
zovision Avatar answered Sep 18 '22 05:09

zovision