gpt4 book ai didi

python - Django REST框架: create and update an object with a nested object value (instead of Primary Key)

转载 作者:太空宇宙 更新时间:2023-11-03 16:58:53 25 4
gpt4 key购买 nike

我有两种型号,一种是国家/地区型号,一种是办公室型号。办公室模型有一个到国家/地区模型的ForeignKey:

class Country(TranslatableModel):
iso = models.CharField(
max_length=2, verbose_name=_('iso code'),
help_text="ISO 3166 ALPHA-2 code")
translations = TranslatedFields(
name=models.CharField(max_length=100, verbose_name=_('name')),
)



class Office(models.Model):
country = models.ForeignKey(
Country, related_name='country', verbose_name=_('country'))

现在我想编写一个 django-rest-framework-serializer 来简单地发送 {"country": "us"} 以获得国家/地区模型的 ForeingKey。

我怎样才能实现这个目标?

最佳答案

只读

简单地发送该表示到客户端(只读,不处理从反序列化表示创建对象)

class OfficeSerializer(serializers.ModelSerializer):
country = serializers.Field(source='country.iso') # this field of the serializer
# is read-only

如您所见,它将从您的 office 实例读取 country.iso,解析为 'us',例如,然后放入名为 'country' 的序列化器键中,输出为 {'country': 'us'}

可写嵌套字段

现在为了完成此任务,让我们编写一个自定义 OfficeSerializer.create():

def create(self, validated_data):
# This expects an input format of {"country": "iso"}

# Instead of using the ID/PK of country, we look it up using iso field
country_iso = validated_data.pop('country')
country = Country.objects.get(iso=country_iso)

# Create the new Office object, and attach the country object to it
office = Office.objects.create(country=country, **validated_data)

# Notice I've left **validated_data in the Office object builder,
# just in case you want to send in more fields to the Office model

# Finally a serializer.create() is expected to return the object instance
return office

至于 OfficeSerializer.update() ,它是类似的:

def update(self, instance, validated_data):
# instance is your Office object
# You should update the Office fields here
# instance.field_x = validated_data['field_x']

# Let's grab the Country object again

country_iso = validated_data.pop('country')
country = Country.objects.get(iso=country_iso)

# Update the Office object
instance.country = country
instance.save()

return instance

关于python - Django REST框架: create and update an object with a nested object value (instead of Primary Key),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35181118/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com