Django REST框架:使用嵌套对象值(而不是主键)创建和更新对象 [英] Django REST Framework: create and update an object with a nested object value (instead of Primary Key)
问题描述
class国家(TranslatableModel):
iso = models.CharField (
max_length = 2,verbose_name = _('iso code'),
help_text =ISO 3166 ALPHA-2代码)
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 ')#这个序列化程序的字段
#是只读
正如你所见,将从您的办公室
实例中读取 country.iso
,解析为 'us'
例如,如果输出的 {',则将其放入一个名为
'country'
国家':'我们'}
可写嵌套字段
现在完成这个,我们写一个自定义的 OfficeSerializer.create()
:
def create(self,validated_data):
#这个输入格式是{country:iso}
#而不是使用国家/地区的ID / PK,我们查找使用iso字段
country_iso = validated_data.pop('country')
c ountry = Country.objects.get(iso = country_iso)
#创建新的Office对象,并将国家/地区对象附加到
office = Office.objects.create(country = country, ** validated_data)
#注意事项我已将** validated_data放在Office对象生成器
#中,以防万一您想将更多的字段发送到Office模型
#最后一个serializer.create()预计返回对象实例
return office
对于 OfficeSerializer.update()
,类似于:
def update(self,instance,validated_data):
#instance是你的Office对象
#你应该在这里更新Office字段
#instance.field_x = validated_data ['field_x']
#再次获取Country对象
country_iso = validated_data.pop('country')
country = Country.objects.get(iso = country_iso)
#更新Office对象
instance.country = country
instance.save()
返回实例
I have two models one Country and one Office model. The office model has a ForeignKey to the Country model:
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'))
Now I want to write a django-rest-framework-serializer to send simply {"country": "us"}
to get a ForeingKey to the Country Model.
How can I achieve this?
Read-only
To simply send that representation to the client (read-only, not dealing with creating objects from their deserialized representation)
class OfficeSerializer(serializers.ModelSerializer):
country = serializers.Field(source='country.iso') # this field of the serializer
# is read-only
As you can see, it'll read will read country.iso
from your office
instance, which resolves to 'us'
e.g., then gets put into a serializer key called 'country'
, given you an output of {'country': 'us'}
Writable nested field
Now to complete this, let's write a custom 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
As for a OfficeSerializer.update()
it's similar:
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
这篇关于Django REST框架:使用嵌套对象值(而不是主键)创建和更新对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!