0

我有以下兩種模式與外鍵關係。序列化時相關字段的自定義行爲

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 

這裏反序列化我想通過只city_id在JSON,但在序列化,我想完成全市對象....所以我重寫relatedfield。 ..但我在反序列化中出錯。我也嘗試覆蓋to_internal_value()方法,但在反序列化過程中它沒有被調用。我怎樣才能做到這一點??

+0

嘗試PrimaryKeyRelatedField。什麼是錯誤? –

+0

@CarltonGibson「to_internal_value()」方法沒有被調用...我調試上面的代碼,它不去那裏.. – Naresh

回答

0

我解決它...其實我設置readonly=True城市的關係,但與只讀只to_representation()得到所謂不to_internal_value() ...所以我經過查詢集...