我有以下型号

class MyModel(models.Model):
    start = models.TimeField()
    finish = models.TimeField()
    penalty = models.IntegerField(blank=True, default=0)  # penalty in minutes

以及管理中的以下queryset注释
def get_queryset(self, request):
    qs = super().get_queryset(request)
    qs = qs.annotate(
        total_time=ExpressionWrapper(
            F("finish") - F("start") + F("penalty") * 60,
            output_field=DurationField()
        )
    )
    return qs

当我检查penalty != 0行的注释值时,会得到类似datetime.timedelta(0, 1800, 1800)的结果(在本例中,惩罚是30分钟)。
不过,我希望时间增量类似于datetime.timedelta(0, 3600)。有人能解释一下吗?
我也试过
def get_queryset(self, request):
    qs = super().get_queryset(request)
    qs = qs.annotate(
        duration=ExpressionWrapper(
            F("finish") - F("start"),
            output_field=DurationField()
        )
    )
    qs = qs.annotate(
        total_time=ExpressionWrapper(
            F("duration") + F("route_shortening_penalty") * 60,
            output_field=DurationField()
        )
    )
    return qs

甚至
def get_queryset(self, request):
    qs = super().get_queryset(request)
    qs = qs.annotate(
        duration=ExpressionWrapper(
            F("finish") - F("start"),
            output_field=DurationField()
        ),
        penalty_duration=ExpressionWrapper(
            F("penalty") * 60,
            output_field=DurationField()
        )
    )
    qs = qs.annotate(
        total_time=ExpressionWrapper(
            F("duration") + F("penalty_duration"),
            output_field=DurationField()
        )
    )
    return qs

两者都会导致
Traceback (most recent call last):
  File "/home/dm/.virtualenvs/test/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/home/dm/.virtualenvs/test/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/home/dm/.virtualenvs/test/lib/python3.6/site-packages/django/core/handlers/base.py", line 124, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/dm/.virtualenvs/test/lib/python3.6/site-packages/django/contrib/admin/options.py", line 604, in wrapper
    return self.admin_site.admin_view(view)(*args, **kwargs)
  File "/home/dm/.virtualenvs/test/lib/python3.6/site-packages/django/utils/decorators.py", line 142, in _wrapped_view
    response = view_func(request, *args, **kwargs)
  File "/home/dm/.virtualenvs/test/lib/python3.6/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func
    response = view_func(request, *args, **kwargs)
  File "/home/dm/.virtualenvs/test/lib/python3.6/site-packages/django/contrib/admin/sites.py", line 223, in inner
    return view(request, *args, **kwargs)
  File "/home/dm/.virtualenvs/test/lib/python3.6/site-packages/django/utils/decorators.py", line 45, in _wrapper
    return bound_method(*args, **kwargs)
  File "/home/dm/.virtualenvs/test/lib/python3.6/site-packages/django/utils/decorators.py", line 142, in _wrapped_view
    response = view_func(request, *args, **kwargs)
  File "/home/dm/.virtualenvs/test/lib/python3.6/site-packages/django/contrib/admin/options.py", line 1793, in changelist_view
    'selection_note': _('0 of %(cnt)s selected') % {'cnt': len(cl.result_list)},
  File "/home/dm/.virtualenvs/test/lib/python3.6/site-packages/django/db/models/query.py", line 250, in __len__
    self._fetch_all()
  File "/home/dm/.virtualenvs/test/lib/python3.6/site-packages/django/db/models/query.py", line 1186, in _fetch_all
    self._result_cache = list(self._iterable_class(self))
  File "/home/dm/.virtualenvs/test/lib/python3.6/site-packages/django/db/models/query.py", line 63, in __iter__
    for row in compiler.results_iter(results):
  File "/home/dm/.virtualenvs/test/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1009, in apply_converters
    value = converter(value, expression, connection)
  File "/home/dm/.virtualenvs/test/lib/python3.6/site-packages/django/db/backends/base/operations.py", line 573, in convert_durationfield_value
    return datetime.timedelta(0, 0, value)
TypeError: unsupported type for timedelta microseconds component: str

我正在使用Python 3.6.7Django==2.1.7SQLite version 3022000

最佳答案

如果你得到的是datetime.timedelta(0, 1800, 1800)而不是正确的datetime.timedelta(0, 3600),那么你显然就快到了。
我假设1800秒是F("finish")F("start")之间的差,而1800微秒来自F("penalty") * 60
乘以60*1000*1000而不是60penalty从分钟转换为微秒:

total_time=ExpressionWrapper(
    F("finish") - F("start") + F("penalty") * 60000000,
    output_field=DurationField()
)

关于python - Django和SQLite:DurationField算术,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55386878/

10-11 23:27