DRF序列化程序可读 - 可写的非模型字段

时间:2017-12-06 13:41:39

标签: django django-rest-framework

在使用Django / DRF的项目中;我有以下模型结构:

class City(models.Model):
    name = models.CharField(max_length=100)

class Company(models.Model):
    city = models.ForeignKey(City)
    .
    .

遵循公司模型的序列化程序结构:

class CompanySerializer(serializers.ModelSerializer):    
    city_name = serializers.CharField(write_only=True)
    .
    .

    class Meta:
        model = Company
        fields = ('city_name',)

    def create(self, validated_data):

        # Get city
        city_name = validated_data.pop('city_name')
        try: 
            city = City.objects.get(name__iexact=city_name)
        except City.DoesNotExist:
            city = City.objects.create(name=city_name.title())

        company = Company.objects.create(city=city, **validated_data)

        return company

在通过序列化程序创建公司时,用户提供了city_name,如果不存在,我创建一个具有该名称的新城市,或者如果存在,则使用现有条目。在这个结构中,我希望能够在返回公司时返回city_name字段。它不是模型上的字段,所以我可以正常使用SerializerMethodField,但我也希望这个字段也是可写的。我有什么选择吗?

2 个答案:

答案 0 :(得分:1)

我认为,您的解决方案很容易添加source并删除write_only

city_name = serializers.CharField(source='city.name')

更改为此方法后,您可以在创建或更新方法中获取城市名称,如下所示:

city_data = validated_data.pop('city')
city_name = city_data.get('name')

答案 1 :(得分:0)

更好的方法是创建两个序列化程序

class CitySerializer(serializers.ModelSerializer):
    class Meta:
        model = City
        fields = ('name')

class CompanySerializer(serializers.ModelSerializer):
    city = CitySerializer(write_only=True)

    class Meta:
        model = Company
        fields = ('city',)

    def create(self, validated_data):

        # Get city
        city = validated_data.pop('city')
        try:
            city = City.objects.get(name__iexact=city)
        except City.DoesNotExist:
            city = City.objects.create(name=city.title())

        company = Company.objects.create(city=city, **validated_data)

        return company