在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处理同时创建Address
和Person
。例如,当我发布以下内容时:
{
'name': 'Alex',
'address': {
'address_line': "1 Here"
}
}
创建Person
并创建Address
,Person
指向新创建的Address
。
如果已经Address
已经有Address
,那么不创建新Address
但重用现有address_line
的最佳方式是什么?即如果我想制作address_line
字段unique
? (此对象重复使用有时称为“实习”)
如果有两个地址字段address_line1
和address_line2
怎么办?如果已存在Address
两个字段,我想重用Address
对象(即unique_together=(address_line1, address_line2)
)?
答案 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)
希望这会有所帮助:)