【问题标题】:How to apply function to field in values_list lookup如何将函数应用于 values_list 查找中的字段
【发布时间】: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


【解决方案1】:

如果您使用的是 Postgres:

from django.db.models import F
from django.db.models.expressions import Func
comments = Comment.objects.annotate(
    age=Func(F('date'), function='AGE') # other functions can be found here https://www.postgresql.org/docs/9.1/functions-datetime.html
).values_list('age')

或者对于更多的数据库不可知的解决方案

from django.db.models import F
from django.db.models.expressions import Value
from django.utils import timezone
comments = Comment.objects.annotate(
    age=Value(timezone.now()) - F('date') # subtract the comment.date from timezone.now()
).values_list('age')

【讨论】:

  • 我使用了第二种解决方案,因为我没有使用 Postgres,它引发了错误:TypeError: expected string or bytes-like object
  • 你用的是什么数据库?
  • 由于我是在本地测试,所以我使用的是默认sqlite。
  • 我已将其添加到问题中
  • 你可以试试age=timezone.now() - F('date')(不带Value(...))
【解决方案2】:

嗯,我通过改变解决问题的方法来修复了我的错误。

            {
                "username": comment.owner.username,
                "text": comment.text,
                "date": timesince.timesince(comment.date),
                "likes": comment.likes,
                "picture": comment.owner.customuser.picture.url
            } for comment in Comment.objects.filter(reply_to__pk__exact=pk)
        ]

虽然这只是避免了问题,但它解决了它!

【讨论】:

    猜你喜欢
    • 2014-10-20
    • 1970-01-01
    • 2021-04-19
    • 1970-01-01
    • 2020-05-25
    • 2013-05-27
    • 2019-12-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多