我可以在我的Django模型中成功过滤给定年份,但我找不到列出有效年份的方法,以便用户可以访问它们.
我有一个带有定义的'datetime'字段的django模型,因此最初命名为'date'.在我的模板中,我可以成功访问'bar.date.date.year'字段,因此我知道它存在,但是当我尝试以下功能时......
blog_years=[]
for entry in blog_entries:
if entry.date.date.year not in blog_years:
blog_years.append(entry.date.date.year)
Run Code Online (Sandbox Code Playgroud)
我被告知"'builtin_function_or_method'对象没有属性'year'"
我只能假设我踩到了我不熟悉的Python的某些方面,但我无法弄清楚它是什么.我很确定它必须是语法,但过去那......
kop*_*die 15
Django有一种优雅而有效的方式.您可以从他们的文档https://docs.djangoproject.com/en/1.9/ref/models/querysets/#dates查看 但是要查看它
Entry.objects.dates('pub_date', 'year')
Run Code Online (Sandbox Code Playgroud)
这将在查询中显示不同的年份值.
如果你使用postgres,你可以做到
BlogEntry.objects.extra(select={"year": "EXTRACT(YEAR FROM date)"}).distinct().values_list("year", flat=True)
Pythonset不允许重复,所以如果你想要一个不同年份的列表:
blog_years = list(set([entry.date.year for entry in blog_entries]))
或者,您可以使用distinct():
blog_years = blog_entries.distinct(entry__date__year).values(entry__date__year)
当然,根据您的模型调整上述内容。
第一个.date访问日期时间对象。
第二个.date是访问日期时间对象上的方法,该方法返回日期对象但不调用它(此步骤是不必要的)。
最后一部分(您编写的方式)是尝试访问year日期方法的属性,而不是访问日期方法调用结果year的属性。
更正代码以查看差异,它看起来像这样......
blog_years=[]
for entry in blog_entries:
if entry.date.date().year not in blog_years:
blog_years.append(entry.date.date().year)
Run Code Online (Sandbox Code Playgroud)
但你应该做的更像是这样......
blog_years=[]
for entry in blog_entries:
if entry.date.year not in blog_years:
blog_years.append(entry.date.year)
Run Code Online (Sandbox Code Playgroud)
因为 datetime 对象也具有 date 属性。
| 归档时间: |
|
| 查看次数: |
5605 次 |
| 最近记录: |