Django:过滤日期时间字段*仅*年值? [英] Django: Filtering datetime field by *only* the year value?

查看:128
本文介绍了Django:过滤日期时间字段*仅*年值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试吐出一个django页面,其中列出了创建年份的所有条目。所以,例如:

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

2010:


  • 注4

  • Note 4

注5

注6

2009:


  • 注1

  • Note 1

注2

注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

我尝试了几种不同的方法,但似乎在每一条路上遇到障碍。我猜测一个有效的group by方法会做窍门(PostGres DB后端),但是我似乎找不到支持它的任何Django功能。我尝试从数据库中获取个人年数,但是我努力寻找一种仅按年值过滤日期时间字段的方法。最后,我尝试添加note_year @property,但是由于它是派生的,我无法过滤这些值。

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.

有什么建议可以做到这一点吗?我认为这应该很简单,但是我有一个heckuva时间。任何想法都非常感激。

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.

推荐答案

构造自定义SQL或使用

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.

这篇关于Django:过滤日期时间字段*仅*年值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆