在我的Django模型中,我可以成功地按给定年份进行过滤,但我很难找到一种方法来列出有效年份,以便用户可以访问它们。
我有一个django模型,有一个定义的'datetime‘字段,哦-所以-最初命名为'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)有人告诉我"'builtin_function_or_method‘对象没有’year‘属性“
我只能假设我被我不熟悉的Python的某些方面绊倒了,但我不知道它是什么,我很确定它必须是语法上的,但除此之外...
发布于 2012-04-19 02:02:34
第一个.date访问datetime对象。
第二个.date访问datetime对象上的一个方法,该方法返回一个date对象,但不调用它(这一步是不必要的)。
最后一部分(您编写的方式)是尝试访问date方法的year属性,而不是访问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)但你应该做的更像这样...
blog_years=[]
for entry in blog_entries:
if entry.date.year not in blog_years:
blog_years.append(entry.date.year)因为datetime对象也有date属性。
发布于 2016-04-19 00:18:32
Django有一种优雅而高效的方式来实现这一点。您可以从他们的文档中查看https://docs.djangoproject.com/en/3.0/ref/models/querysets/#dates,但要查看它
Entry.objects.dates('pub_date', 'year')这将在查询中显示不同的年份值。
发布于 2012-10-27 22:55:29
Python set不允许重复,所以如果您想要不同年份的列表:
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)
当然,请根据您的模型调整以上内容。
https://stackoverflow.com/questions/10215164
复制相似问题