问题描述
在使用Django/DRF的项目中;我具有以下模型结构:
On a project with Django / DRF; I have the following model structure:
class City(models.Model):
name = models.CharField(max_length=100)
class Company(models.Model):
city = models.ForeignKey(City)
.
.
以及以下用于公司模型的序列化器结构:
And following serializer structure for Company model:
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,但我也希望该字段也可写.我在这里有什么选择吗?
While creating a company through the serializer, user provides a city_name, I create a new city with that name if not exists or use an existing entry if exists. In this structure, I want to be able to return city_name field while returning companies. It is not a field on the model, so I could use SerializerMethodField normally, but I also want this field to be writable as well. Do I have any options here?
推荐答案
我认为,您的解决方案很容易添加源并删除 write_only
:
i think, your solution is simple to add source and remove write_only
:
city_name = serializers.CharField(source='city.name')
更改为该方法后,您可以按以下方法在创建或更新方法中获取城市名称:
After changing to this approach, you can get city name in create or update methods as follows:
city_data = validated_data.pop('city')
city_name = city_data.get('name')
这篇关于DRF序列化器可读-可写的非模型字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!