완성을 위해 최근 프로젝트에서 필요했기 때문에 to_internal_value()
구현을 추가하고 있습니다.
유형
을 확인하는 방법 그것의 다른 "클래스"를 구별하는 가능성을 가지고 편리한; 그래서 나는이 목적을 위해 기본 다형성 모델로 type 속성을 추가했습니다 :
는
class GalleryItem(PolymorphicModel):
gallery_item_field = models.CharField()
@property
def type(self):
return self.__class__.__name__
이 "필드"로 type
를 호출하고 "전용 필드를 읽기"할 수 있습니다.
type
에는 파이썬 클래스 이름이 포함됩니다.
당신은 "필드"로 type
를 추가하고 모두를 사용하려는 경우 가 (당신이 생각하는 모든 직렬 변환기의 유형 필드를 지정해야 "필드 만 읽기"수 시리얼에
을 유형을 추가 하위 모델)
class PhotoSerializer(serializers.ModelSerializer):
class Meta:
model = models.Photo
fields = (..., 'type',)
read_only_fields = (..., 'type',)
class VideoSerializer(serializers.ModelSerializer):
class Meta:
model = models.Video
fields = (..., 'type',)
read_only_fields = (..., 'type',)
class GalleryItemModuleSerializer(serializers.ModelSerializer):
class Meta:
model = models.GalleryItem
fields = (..., 'type',)
read_only_fields = (..., 'type',)
def to_representation(self, obj):
pass # see the other comment
def to_internal_value(self, data):
"""
Because GalleryItem is Polymorphic
"""
if data.get('type') == "Photo":
self.Meta.model = models.Photo
return PhotoSerializer(context=self.context).to_internal_value(data)
elif data.get('type') == "Video":
self.Meta.model = models.Video
return VideoSerializer(context=self.context).to_internal_value(data)
self.Meta.model = models.GalleryItem
return super(GalleryItemModuleSerializer, self).to_internal_value(data)
나는'to_native' 방법에 대한 문서를 찾을 수 없습니다. 언제 불러? –
http://www.django-rest-framework.org/topics/3.0-announcement/#changes-to-the-custom-field-api –
POST와 PUT이 약간 더 어려울 수도 있습니다.) 사용자가 제출하고자하는 것을 결정할 필요가 있기 때문에, 검증 전에 (필드가 빠져 있다면 확실하지 않을 수도 있습니다). IMHO, 쓰기 요청에 별도의 끝점을 사용하는 것이 더 깔끔합니다. – WhyNotHugo