在Django Rest Framework嵌套Serializer中重用现有对象

时间:2014-10-08 00:01:28

标签: django django-models django-rest-framework

在drf中使用嵌套的Serializers时,如何重新使用引用的对象:

假设我有以下两个Model

class Address(models.Model):
    address_line = models.CharField(max_length=45)

class Person(models.Model):
    name = models.CharField(max_length=45)
    address = models.ForeignKey(Address)

Serializer s:

class AddressSerializer(serializers.ModelSerializer):
    class Meta:
        model = Address

class PersonSerializer(serializers.ModelSerializer):
    address = AddressSerializer()

    class Meta:
        model = Person

现在,Serializers处理同时创建AddressPerson。例如,当我发布以下内容时:

{
    'name': 'Alex',
    'address': {
        'address_line': "1 Here"
    }
}

创建Person并创建AddressPerson指向新创建的Address

如果已经Address已经有Address,那么不创建新Address但重用现有address_line的最佳方式是什么?即如果我想制作address_line字段unique? (此对象重复使用有时称为“实习”)

如果有两个地址字段address_line1address_line2怎么办?如果已存在Address两个字段,我想重用Address对象(即unique_together=(address_line1, address_line2))?

1 个答案:

答案 0 :(得分:2)

最近我遇到了类似的问题,使用以下方法解决了它(代码尚未经过测试,仅供参考):

class PersonSerializer(serializers.ModelSerializer):
    address = AddressSerializer()

    class Meta:
        model = Person

    def create(self, validated_data):
        # pop the validated user data
        # assuming its a required field,
        # it will always be there in validated_data
        address = validated_data.pop('address')

        try:
            address = Address.objects.get(address_line=address.get('address_line'))
        except ObjectDoesNotExist:
            address_serializer = AddressSerializer(data=address)
            address_serializer.is_valid(raise_exception=True)
            address = address_serializer.save()
        else:
            # save the user and update the validated_data for setting up profile
            validated_data['address'] = address

        return super(PersonSerializer, self).create(validated_data)

希望这会有所帮助:)