我有两个模型,一个国家和一个Office模型。办公室模型有一个ForeignKey to the Country模型:
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。
我怎样才能做到这一点?
答案 0 :(得分:1)
简单地将表示发送到客户端(只读,而不是处理从反序列化表示中创建对象)
class OfficeSerializer(serializers.ModelSerializer):
country = serializers.Field(source='country.iso') # this field of the serializer
# is read-only
正如您所看到的,它将会从您的country.iso
实例中读取office
,该实例将解析为'us'
,例如,然后将其放入名为{{的序列化程序密钥中1}},给出输出'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()