1

我有以下脚本:

import django
import os
import sys
from django.db import transaction
from xxx.models import File
import reversion
from reversion.models import Version
from datetime import datetime

# Creating a file entry in here:
with reversion.create_revision():
    f = File(name="foo", mtime=datetime.now(), ctime=datetime.now(), size=33)
    f.save()

    reversion.set_comment("Revision 1")

# Modifying it:
with reversion.create_revision():
    f.mtime = datetime.now()
    f.ctime = datetime.now()
    f.size = 23
    f.save()

    reversion.set_comment("Revision 2")

versions = Version.objects.get_for_object(f)
print(len(versions))
for i in range(len(versions)):
    print(versions[i])
    print(versions[i].field_dict) # ERROR!
    print(versions[i].revision.__dict__)

这是长的回溯:

Traceback (most recent call last):
  File "/home/rzhang2/pythons/anaconda2/envs/python36/lib/python3.6/site-packages/django/core/serializers/python.py", line 166, in Deserializer
    data[field.name] = field.to_python(field_value)
  File "/home/rzhang2/pythons/anaconda2/envs/python36/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 1246, in to_python
    params={'value': value},
django.core.exceptions.ValidationError: ["'2018-04-24T21:38:14.319' value has an invalid date format. It must be in YYYY-MM-DD format."]

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/rzhang2/pythons/anaconda2/envs/python36/lib/python3.6/site-packages/reversion/models.py", line 241, in _object_version
    return list(serializers.deserialize(self.format, data, ignorenonexistent=True))[0]
  File "/home/rzhang2/pythons/anaconda2/envs/python36/lib/python3.6/site-packages/django/core/serializers/json.py", line 69, in Deserializer
    yield from PythonDeserializer(objects, **options)
  File "/home/rzhang2/pythons/anaconda2/envs/python36/lib/python3.6/site-packages/django/core/serializers/python.py", line 168, in Deserializer
    raise base.DeserializationError.WithData(e, d['model'], d.get('pk'), field_value)
django.core.serializers.base.DeserializationError: ["'2018-04-24T21:38:14.319' value has an invalid date format. It must be in YYYY-MM-DD format."]: (xxx.file:pk=foo) field_value was '2018-04-24T21:38:14.319'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "play_with_reversion.py", line 47, in <module>
    print(versions[i].field_dict)
  File "/home/rzhang2/pythons/anaconda2/envs/python36/lib/python3.6/site-packages/django/utils/functional.py", line 36, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/home/rzhang2/pythons/anaconda2/envs/python36/lib/python3.6/site-packages/reversion/models.py", line 283, in field_dict
    field_dict = self._local_field_dict
  File "/home/rzhang2/pythons/anaconda2/envs/python36/lib/python3.6/site-packages/django/utils/functional.py", line 36, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/home/rzhang2/pythons/anaconda2/envs/python36/lib/python3.6/site-packages/reversion/models.py", line 261, in _local_field_dict
    object_version = self._object_version
  File "/home/rzhang2/pythons/anaconda2/envs/python36/lib/python3.6/site-packages/django/utils/functional.py", line 36, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/home/rzhang2/pythons/anaconda2/envs/python36/lib/python3.6/site-packages/reversion/models.py", line 244, in _object_version
    "object_repr": self.object_repr,
reversion.errors.RevertError: Could not load name: foo mtime: 2018-04-24 21:30:15.468835 ctime: 2018-04-24 21:30:15.468838 size: 23 version - incompatible version data.

所以很明显field_dict,在反序列化过程中出现了问题。

然后我尝试重新启动所有修订并再次执行此操作:

python manage.py deleterevisions

我再次运行它,它仍然给出了同样的错误。

我的架构相当简单:

@reversion.register
class File(models.Model):
    name = models.CharField(max_length=400, primary_key=True)
    mtime = models.DateField()
    ctime = models.DateField()
    size = models.IntegerField()

    def __str__(self):
        return "name: {} mtime: {} ctime: {} size: {}".format(self.name, self.mtime, self.ctime, self.size)

到底发生了什么?

注意:如果我删除该特定行,这是我的输出(运行python manage.py deleterevisions刷新后):

3
name: foo mtime: 2018-04-24 21:45:26.497498 ctime: 2018-04-24 21:45:26.497501 size: 23
{'_state': <django.db.models.base.ModelState object at 0x7f6e7aa16f28>, 'id': 42, 'date_created': datetime.datetime(2018, 4, 24, 21, 45, 26, 497470, tzinfo=<UTC>), 'user_id': None, 'comment': 'Revision 2'}
name: foo mtime: 2018-04-24 21:45:26.475707 ctime: 2018-04-24 21:45:26.475711 size: 33
{'_state': <django.db.models.base.ModelState object at 0x7f6e7aa24080>, 'id': 41, 'date_created': datetime.datetime(2018, 4, 24, 21, 45, 26, 470003, tzinfo=<UTC>), 'user_id': None, 'comment': 'Revision 1'}
name: foo mtime: 2018-04-24 ctime: 2018-04-24 size: 23
{'_state': <django.db.models.base.ModelState object at 0x7f6e7aa24198>, 'id': 40, 'date_created': datetime.datetime(2018, 4, 24, 21, 45, 13, 671939, tzinfo=<UTC>), 'user_id': None, 'comment': 'Initial version.'}
4

1 回答 1

2

所以我想出了原因。出于某种原因,将datetime对象传递给DateField我的模型类型是无效的。我不知道有一个DateTimeField正是为此目的。

当我传入一个对象时,Django 没有抱怨datetime,它似乎可能进行了隐式转换。但是,该库django-reversion可能会在隐式转换之前获取该值,并尝试将对象反序列化为模型,但该模型并未证明使用datetime对象成功。

根据以下文档DateTimeField

日期和时间,在 Python 中由 datetime.datetime 实例表示。

于 2018-04-25T15:26:49.343 回答