【发布时间】:2020-03-30 22:24:16
【问题描述】:
我的代码行是:
replies = Comment.objects.filter(reply_to__pk__exact=pk).annotate(dates=timesince.timesince('date'))\
.order_by('-dates')\
.values_list("owner__username", "text", "dates", "likes", "owner__customuser__picture")
我希望结果中的日期列由timesince.timesince 函数转换。相反,它会抛出如下错误:
AttributeError: 'str' object has no attribute 'year'
我该如何解决这个问题?
编辑 1:根据@GrandPhuba 的要求,实施第二个解决方案后的追溯是
Traceback (most recent call last):
File "/home/lord-sarcastic/.local/share/virtualenvs/Bonychicken-xy3Z_xpD/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/home/lord-sarcastic/.local/share/virtualenvs/Bonychicken-xy3Z_xpD/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/lord-sarcastic/.local/share/virtualenvs/Bonychicken-xy3Z_xpD/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/lord-sarcastic/Bonychicken/main/views.py", line 374, in get_replies
print(comments)
File "/home/lord-sarcastic/.local/share/virtualenvs/Bonychicken-xy3Z_xpD/lib/python3.8/site-packages/django/db/models/query.py", line 252, in __repr__
data = list(self[:REPR_OUTPUT_SIZE + 1])
File "/home/lord-sarcastic/.local/share/virtualenvs/Bonychicken-xy3Z_xpD/lib/python3.8/site-packages/django/db/models/query.py", line 276, in __iter__
self._fetch_all()
File "/home/lord-sarcastic/.local/share/virtualenvs/Bonychicken-xy3Z_xpD/lib/python3.8/site-packages/django/db/models/query.py", line 1261, in _fetch_all
self._result_cache = list(self._iterable_class(self))
File "/home/lord-sarcastic/.local/share/virtualenvs/Bonychicken-xy3Z_xpD/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1095, in apply_converters
value = converter(value, expression, connection)
File "/home/lord-sarcastic/.local/share/virtualenvs/Bonychicken-xy3Z_xpD/lib/python3.8/site-packages/django/db/backends/sqlite3/operations.py", line 260, in convert_datetimefield_value
value = parse_datetime(value)
File "/home/lord-sarcastic/.local/share/virtualenvs/Bonychicken-xy3Z_xpD/lib/python3.8/site-packages/django/utils/dateparse.py", line 107, in parse_datetime
match = datetime_re.match(value)
TypeError: expected string or bytes-like object
【问题讨论】:
-
这不是源于此,您在某处写过
.year,其中该对象是一个字符串,而不是datetime对象(或类似的东西)。 -
好吧,我的代码中没有类似的东西。我没有在
dates列中调用任何属性
标签: django django-views python-3.6 django-queryset