использовать изображения.копирование в рекурсивной deepcopy

У меня есть базовая модель, которая копирует модель в contructor:

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

Моя проблема в том, что некоторые модели имеют ImageField, и когда я пытаюсь скопировать, я получаю AttributeError. Я нашел решение для этой ошибки здесь, что говорит «использовать изображение.copy () вместо copy.deepcopy ().

Могу ли я реализовать образ.copy () in a recursive deepcopy when the field is a image?

Большое спасибо!

EDIT: это трассировка:

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 ответ

  1. Я думаю, что лучший способ-это добавить метод 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