序列化时RelatedField的自定义行为

时间:2016-02-23 07:36:35

标签: python django serialization django-rest-framework deserialization

下面有两个带有外键关系的模型。

class City(TimeStampedModel):
    uuid = models.UUIDField(default=uuid.uuid4, editable=False)
    long_name = models.CharField(max_length=200)
    short_name = models.CharField(max_length=200)

class Address(TimeStampedModel):
         address_object = GenericForeignKey('address_content_type', 'object_id')
    address1 = models.CharField(max_length=200)
    address2 = models.CharField(max_length=200, null=True)
    landmark = models.CharField(max_length=200, null=True)
    city = models.ForeignKey(City, related_name='address_city')

我已为地址

定义了以下序列化器
class CityRelation(serializers.RelatedField):
    def to_representation(self, value):
        if isinstance(value, City):
            return CitySerializer(value).data

class AddressBookSerializer(serializers.ModelSerializer):
    city = CityRelation(read_only=True)

    class Meta:
        model = Address
        fields = ('id', 'uuid', 'address1', 'address2', 'landmark', 'city')
    @atomic
    def create(self, validated_data):
        address_book = Address(**validated_data)
        address_book.save()
        return address_book

    def update(self, instance, validated_data):
        instance.address1 = validated_data['address1']
        instance.address2 = validated_data['address2']
        instance.landmark = validated_data['landmark']
        instance.city = validated_data['city']
        instance.save()
        return instance

这里虽然反序列化我想只传递JSON中的city_id但是在序列化时我想要完整的城市对象....所以我覆盖相关字段...但是我在反序列化中遇到错误。我还尝试覆盖to_internal_value()方法但在反序列化期间没有调用。我怎么能这样做?

1 个答案:

答案 0 :(得分:0)

我解决了......实际上我为城市关系设置readonly=True但是只读to_representation()而不是to_internal_value() ...所以我通过了查询集......