2015-01-14 5 views
4

Generic Relation을 세부적으로 직렬화하려는 모델이 있습니다.Django Rest Framework 시리얼 라이저의 조건부 필드

class AType(models.Model): 
    foo = CharField() 


class BType(models.Model): 
    bar = PositiveIntegerField() 


class ToSerialize(models.Model): 
    scope_limit = models.Q(app_label="app", model="atype") | \ 
        models.Q(app_label="app", model="btype") 
    content_type = models.ForeignKey(ContentType, limit_choices_to=scope_limit) 
    object_id = models.PositiveIntegerField() 
    content_object = generic.GenericForeignKey('content_type', 'object_id') 

내가 같이하는 ToSerialize의 뷰셋의 목록 방법에 대한 JSON을 싶습니다

[ 
    { 
     "atype": { "id": 1, "foo": "a" } 
    }, 
    { 
     "atype": { "id": 2, "foo": "b" } 
    }, 
    { 
     "btype": { "id": 1, "bar": "1" } 
    }, 
    { 
     "btype": { "id": 2, "bar": "2" } 
    } 
] 

나는 ToSerialize 객체의 "생산 뷰셋 조건 필드의 시리얼을 할 수있는 방법이 있나요 "이 효과를 얻을 수있는 content_type/object_id를 기반으로합니까?

답변

2

사용 SerializeMethodField : 값이없는 경우

class YourSerializer(serializers.ModelSerializer): 
    your_conditional_field = serializers.SerializerMethodField() 

    class Meta: 
     model = ToSerialize 

    def get_your_conditional_field(self, obj): 
     # do your conditional logic here 
     # and return appropriate result 
     return obj.content_type > obj.object_id 
+0

조건부 필드가 결과에서 "제거"할 것인가? –

+0

@GhislainLeveque,'SerializeMethodField'는 모델을 JSON으로 직렬화 할 때만 나타나는 읽기 전용 필드입니다. JSON에서 인스턴스로 deserialize 할 때 값을 지정할 수 없습니다. –

+0

@GhislainLeveque 아니요. 계속 포함됩니다. 나는이 대답이 그 질문을 다루는 지 확신하지 못한다. –

관련 문제