tutorial - python rest framework

Django REST框架:使用嵌套對象值(而不是主鍵)創建和更新對象 (1)


為了簡單地將該表示發送給客戶端( 只讀 ,不處理從反序列化表示中創建對象)

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'}



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


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

    return instance

我有兩個模型一個國家和一個辦公室模型。 辦公室模式的國家模式有一個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到Country模型。