TimeField 和 DurationField int 错误

TimeField and DurationField int error

当 运行ning python manage.py migrate when using DurationField and TimeField both gives me a:

我 运行 进入这个错误
return int(round(value.total_seconds() * 1000000))
AttributeError: 'int' object has no attribute 'total_seconds'

我在这个网站上看到过这个错误,但只针对 Django 1.8。目前,我正在使用 Django 1.10。 我已经尝试了这些建议:

DurationField(default=timedelta()), 
DurationField(), 
DurationField(default=timedelta()), 
DurationField(default=int(timedelta(minutes=20).total_seconds())). 

我的模型目前看起来像:

class SomeModel(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    lunchnumber = models.IntegerField(null=True, blank=True)
    role = models.PositiveSmallIntegerField(choices=ROLE_CHOICES,null=True, blank=True)
    breaktime = models.DurationField(default=timedelta(minutes=45))

    def to_python(self, value):
        if value is None:
            return value
        if isinstance(value, datetime.timedelta):
            return value
        try:
            parsed = parse_duration(value)
        except ValueError:
            pass
        else:
            if parsed is not None:
                return parsed

解决 Prakhar Trivedi 的问题: 我不知道什么值不能正常工作。我假设这是 django 尝试填充数据库 table 的默认值。我有这种印象是因为 ......在get_db_prep_value return int(圆(value.total_seconds() * 1000000)) AttributeError: 'int' 对象没有属性 'total_seconds'

解决 iklinac 的回答:

我进去加了default=timedelta(minutes=45)。我确实从 datetime 导入了它,但我觉得我遗漏了一些东西。我对此很陌生,还没有看到 to_python 函数。我错过了什么我仍然得到同样的错误?

请检查您是否从 datetime 包导入 timedelta :)

from datetime import timedelta

这两个应该有用

DurationField(default=timedelta(minutes=20))
DurationField(default=timedelta())

to_python DurationField 函数如下

    if value is None:
        return value
    if isinstance(value, datetime.timedelta):
        return value
    try:
        parsed = parse_duration(value)
    except ValueError:
        pass
    else:
        if parsed is not None:
            return parsed

如果您仍然遇到 timedelta 问题,您可以使用 parse_duration 代码注释

中所述的其中一种格式
def parse_duration(value):
    """Parses a duration string and returns a datetime.timedelta.

    The preferred format for durations in Django is '%d %H:%M:%S.%f'.

    Also supports ISO 8601 representation.
    """
    match = standard_duration_re.match(value)
    if not match:
        match = iso8601_duration_re.match(value)
    if match:
        kw = match.groupdict()
        if kw.get('microseconds'):
            kw['microseconds'] = kw['microseconds'].ljust(6, '0')
        kw = {k: float(v) for k, v in six.iteritems(kw) if v is not None}
        return datetime.timedelta(**kw)

我遇到了完全相同的问题,iklinac 的回答帮助了我。

一旦我 运行 python manage.py makemigrations 并显示

You are trying to change the nullable field 'duration' on task to non-nullable without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:
 1) Provide a one-off default now (will be set on all existing rows with a null value for this column)
 2) Ignore for now, and let me handle existing rows with NULL myself (e.g. because you added a RunPython or RunSQL operation to handle NULL values in a previous data migration)
 3) Quit, and let me add a default in models.py

所以我将 DurationField 设置为 0 懒惰的原因...

之后错误一直显示...

通过看到这个答案,我发现当 运行 "python manage.py migrate" 它实际上 运行 一个 000x_auto_xxxx.py 在名为 migrations 的文件夹中。所以我发现 .py 文件包含 field=models.DurationField(default=0) 并改成正确的方式,最终解决问题。

希望这对您有所帮助