2017-11-22 6 views
1

나는 장고 프로젝트를 작업하고 데이터베이스 동기화를 위해 객체가 객체를 삭제하지 않도록하기 위해 json 파일에 저장하기로 결정했습니다. 이를 위해 모델의 delete() 메서드를 재정의합니다. 먼저 파일에서 이전에 삭제 한 개체를 검색 한 다음 삭제 된 개체를 추가합니다. 이 새로운 목록을 직렬화하면 AttributeError가 발생합니다.삭제시 모델 객체를 직렬화 할 때 AttributeError

AttributeError: 'DeserializedObject' object has no attribute '_meta'

내가 뭘 잘못하고 있니? 문서에 명시된 바와 같이

def delete(self, *args, **kwargs): 
    force = kwargs.pop("force", None) 

    if force is None: 
     objects_to_delete = list() 
     user_dir_path = os.path.join(STATIC_ROOT, self.user.username) 
     if not os.path.exists(user_dir_path): 
      os.makedirs(user_dir_path) 
     path = os.path.join(user_dir_path, "obj_to_delete.json") 
     if os.path.exists(path): 
      with open(path, "r") as fp: 
       json_str = fp.read() 
       if len(json_str) > 0: 
        objects_to_delete = list(serializers.deserialize(
         "json", 
         json_str, 
         indent=4, 
         use_natural_foreign_keys=True, 
         fields=('pk', 'user', 'slug') 
         )) 

     objects_to_delete.append(self) 

     if objects_to_delete: 
      with open(path, "w") as fp: 
       jsonData = serializers.serialize("json", 
        objects_to_delete, indent=4, 
        use_natural_foreign_keys=True, 
        fields=('pk', 'user', 'slug') 
       ) 
       fp.write(jsonData) 

    super(UserOwnedModel,self).delete(*args, **kwargs) 

답변

1

https://docs.djangoproject.com/en/1.11/topics/serialization/#deserializing-data

의 시리얼에서 역 직렬화하는 방법은 직접 개체를 반환 오히려 DeserializeObject에 포장하지 않습니다 여기에

는 삭제() 코드 . 객체에 액세스하려면 예를 들어 deserialized_object.object를 호출해야합니다.

대신이 시도 할 수 있습니다 :

objects_to_delete = list(obj.object for obj in serializers.deserialize(
    "json", 
    json_str, 
    indent=4, 
    use_natural_foreign_keys=True, 
    fields=('pk', 'user', 'slug') 
    ))