在递归深度复制中使用Image.copy

时间:2016-12-29 12:34:44

标签: python django python-3.x django-models

我在构造函数中复制模型的basemodel:

class BaseModel(models.Model):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.original = copy.deepcopy(self

我的问题是有些模型有ImageField,当我尝试复制时,我得到了AttributeError。我找到了这个错误here的解决方案,它说"使用image.copy()而不是copy.deepcopy()。

当字段是图像时,我可以在递归深度检查中实现image.copy()吗?

非常感谢!

编辑:这是跟踪:

Traceback: 

File "/home/imontilla/.virtualenvs/petycash-django/lib/python3.5/site-packages/PIL/ImageFile.py" in load

139. read = self.load_read

During handling of the above exception ('JpegImageFile' object has no attribute 'load_read'), another exception occurred:

File "/home/imontilla/.virtualenvs/petycash-django/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner

39. response = get_response(request)

File "/home/imontilla/.virtualenvs/petycash-django/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response

187. response = self.process_exception_by_middleware(e, request)

File "/home/imontilla/.virtualenvs/petycash-django/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response

185. response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/home/imontilla/.virtualenvs/petycash-django/lib/python3.5/site-packages/django/views/decorators/csrf.py" in wrapped_view

58. return view_func(*args, **kwargs)

File "/home/imontilla/.virtualenvs/petycash-django/lib/python3.5/site-packages/django/views/generic/base.py" in view

68. return self.dispatch(request, *args, **kwargs)

File "/home/imontilla/.virtualenvs/petycash-django/lib/python3.5/site-packages/rest_framework/views.py" in dispatch

477. response = self.handle_exception(exc)

File "/home/imontilla/.virtualenvs/petycash-django/lib/python3.5/site-packages/rest_framework/views.py" in handle_exception

437. self.raise_uncaught_exception(exc)

File "/home/imontilla/.virtualenvs/petycash-django/lib/python3.5/site-packages/rest_framework/views.py" in dispatch

474. response = handler(request, *args, **kwargs)

File "/home/imontilla/PycharmProjects/api/apps/chats/api.py" in put

107. return self.response_or_errors(serializer, respond_with=serializers.ChatMessageOutputSerializer)

File "/home/imontilla/PycharmProjects/api/apps/core/generics.py" in response_or_errors

31. instance = serializer.save(**kwargs)

File "/home/imontilla/.virtualenvs/petycash-django/lib/python3.5/site-packages/rest_framework/serializers.py" in save

214. self.instance = self.create(validated_data)

File "/home/imontilla/.virtualenvs/petycash-django/lib/python3.5/site-packages/rest_framework/serializers.py" in create

902. instance = ModelClass.objects.create(**validated_data)

File "/home/imontilla/.virtualenvs/petycash-django/lib/python3.5/site-packages/django/db/models/manager.py" in manager_method

85. return getattr(self.get_queryset(), name)(*args, **kwargs)

File "/home/imontilla/.virtualenvs/petycash-django/lib/python3.5/site-packages/django/db/models/query.py" in create

397. obj = self.model(**kwargs)

File "/home/imontilla/PycharmProjects/api/apps/core/models.py" in __init__

22. self.original_instance = copy.deepcopy(self)

File "/home/imontilla/.virtualenvs/petycash-django/lib/python3.5/copy.py" in deepcopy

182. y = _reconstruct(x, rv, 1, memo)

File "/home/imontilla/.virtualenvs/petycash-django/lib/python3.5/copy.py" in _reconstruct

297. state = deepcopy(state, memo)

File "/home/imontilla/.virtualenvs/petycash-django/lib/python3.5/copy.py" in deepcopy

155. y = copier(x, memo)

File "/home/imontilla/.virtualenvs/petycash-django/lib/python3.5/copy.py" in _deepcopy_dict

243. y[deepcopy(key, memo)] = deepcopy(value, memo)

File "/home/imontilla/.virtualenvs/petycash-django/lib/python3.5/copy.py" in deepcopy

182. y = _reconstruct(x, rv, 1, memo)

File "/home/imontilla/.virtualenvs/petycash-django/lib/python3.5/copy.py" in _reconstruct

297. state = deepcopy(state, memo)

File "/home/imontilla/.virtualenvs/petycash-django/lib/python3.5/copy.py" in deepcopy

155. y = copier(x, memo)

File "/home/imontilla/.virtualenvs/petycash-django/lib/python3.5/copy.py" in _deepcopy_dict

243. y[deepcopy(key, memo)] = deepcopy(value, memo)

File "/home/imontilla/.virtualenvs/petycash-django/lib/python3.5/copy.py" in deepcopy

174. rv = reductor(4)

File "/home/imontilla/.virtualenvs/petycash-django/lib/python3.5/site-packages/PIL/Image.py" in __getstate__

639. self.getpalette(),

File "/home/imontilla/.virtualenvs/petycash-django/lib/python3.5/site-packages/PIL/Image.py" in getpalette

1196. self.load()

File "/home/imontilla/.virtualenvs/petycash-django/lib/python3.5/site-packages/PIL/ImageFile.py" in load

143. read = self.fp.read

Exception Type: AttributeError at /chats/6fbd9f3e87f945b99969b2c53e35eb66/messages/image/

Exception Value: 'NoneType' object has no attribute 'read'

1 个答案:

答案 0 :(得分:0)

我认为最好的方法是在您的课程中添加方法copy。在此方法中,您可以控制复制具有不同类型的对象的方式。

class BaseModel(models.Model):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.original = self.copy()

    def copy(self):
        clone = copy.copy(self) # to copy __dict__ only
        for key, value in clone.__dict__.items():
            if isinstance(value, BaseModel):
                clone.__dict__[key] = value.copy() # recoursively
            elif isinstance(value, Image):
                clone.__dict__[key] = value.copy()
            else:
                clone.__dict__[key] = copy.deepcopy(value)
        return clone