Django REST框架:使用嵌套对象值(而不是主键)创建和更新对象

时间:2016-02-03 15:30:02

标签: python django django-rest-framework

我有两个模型,一个国家和一个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。

我怎样才能做到这一点?

1 个答案:

答案 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()