I'm trying to spit out a django page which lists all entries by the year they were created. So, for example:
我正在尝试创建一个django页面,该页面列出了创建它们的年份的所有条目。举个例子:
2010:
2010:
-
Note 4
注意4
-
Note 5
注5
-
Note 6
注6
2009:
2009:
-
Note 1
注1
-
Note 2
注2
-
Note 3
注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.
我尝试过几种不同的方法,但似乎在每条路上都遇到了障碍。我猜想一个有效的“group by”方法可以达到这个目的(PostGres DB后端),但是我似乎找不到任何支持它的Django功能。我试着从数据库中获得独立的年份,但我努力寻找一种方法,仅用年份值来过滤datetime字段。最后,我尝试添加note_year @property,但是因为它是派生的,所以我不能过滤这些值。
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.
有什么好的建议吗?我觉得这应该很简单,但我有很多时间。感谢任何想法。
2 个解决方案
#1
25
Either construct custom SQL or use
要么构造自定义SQL,要么使用
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.
这是基于日期的通用视图的实现方式。
#2
3
You can use django.views.generic.date_based.archive_year or use year field lookup.
您可以使用django.views.generic.date_based。archive_year或使用year字段查找。
#1
25
Either construct custom SQL or use
要么构造自定义SQL,要么使用
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.
这是基于日期的通用视图的实现方式。
#2
3
You can use django.views.generic.date_based.archive_year or use year field lookup.
您可以使用django.views.generic.date_based。archive_year或使用year字段查找。