英文:
Access to the date details in a Django database
问题
I'm currently going over the official Django tutorial. At some point we're shown how to filter keys by the year of the automatically-filled pub_date
column.
>>> Question.objects.get(pub_date__year=current_year)
<Question: What's up?>
But somehow the syntax when calling the year
of the date directly has to be with a .
instead of a __
...
In [56]: q=Question.objects.get(pub_date__year=current_year)
In [57]: q.pub_date__year
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
Cell In [57], line 1
----> 1 q.pub_date__year
AttributeError: 'Question' object has no attribute 'pub_date__year'
In [58]: q.pub_date.year
Out[58]: 2023
Is there some reason it has to be different when called outside of the parenthesis?
英文:
I'm currently going over the official Django tutorial. At some point we're shown how to filter keys by the year of the the automatically-filled pub_date
column.
>>> Question.objects.get(pub_date__year=current_year)
<Question: What's up?>
But somehow the syntax when calling the year
of the date directly has to be with a .
instead of a __
...
In [56]: q=Question.objects.get(pub_date__year=current_year)
In [57]: q.pub_date__year
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
Cell In [57], line 1
----> 1 q.pub_date__year
AttributeError: 'Question' object has no attribute 'pub_date__year'
In [58]: q.pub_date.year
Out[58]: 2023
Is there some reason it has to be different when called outside of the parenthesis?
答案1
得分: 1
q.pub_date 是一个 datetime 对象,它在 Python 中具有名为 year 的属性。这是因为你可以使用点(.)来访问对象属性,所以你必须写 datetime_obj.year 来获取年份。
英文:
The reason behind this is q.pub_date is datetime object and it has the attribute called year in python, its the syntax that you can access the object attributes using dot(.) that's why you have to write datetime_obj.year to get the year.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论