在使用DurationField和TimeField运行python manage.py migrate时,我遇到了这个错误,它们都给了我一个:
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尝试填充该数据库表的默认值。我是因为这种印象 .......在get_db_prep_value中 return int(round(value.total_seconds()* 1000000)) AttributeError:' int'对象没有属性' total_seconds'
解决iklinac的答案:
我进去并添加了默认= timedelta(分钟= 45)。我确实从日期时间导入它但我觉得我错过了一些东西。我是新手,并没有看到to_python函数。我错过了什么我仍然得到同样的错误?
答案 0 :(得分:1)
请检查您是否从datetime包导入timedelta:)
from datetime import timedelta
这两个应该有效
DurationField(default=timedelta(minutes=20))
DurationField(default=timedelta())
DurationField的to_python函数如下
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)
答案 1 :(得分:0)
我遇到了同样的问题,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 migration”时,它实际上在名为migrations的文件夹中运行000x_auto_xxxx.py。所以我发现那个包含field = models.DurationField(default = 0)的.py文件 并以正确的方式进行更改,最后解决问题。
希望这会有所帮助