访问Django数据库中的日期详细信息

huangapple go评论65阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年3月21日 02:47:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/75794170-2.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定