gpt4 book ai didi

django - 重用 Django Rest Framework 嵌套序列化器中的现有对象

转载 作者:行者123 更新时间:2023-12-02 03:20:54 25 4
gpt4 key购买 nike

在 drf 中使用嵌套序列化器时,如何重新使用引用的对象:

假设我有以下两个模型:

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)

使用序列化器:

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

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

class Meta:
model = Person

现在,序列化程序可以同时处理AddressPerson 的创建。例如,当我发布以下内容时:

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

创建一个Person,并创建一个Address,其中Person指向新创建的Address

如果已经存在具有给定的地址,那么不创建新地址而是重用现有地址的最佳方法是什么地址行?即,如果我想让 address_line 字段唯一? (这种对象重用有时称为“实习”)

如果有两个地址字段 address_line1address_line2 并且我想重用 Address 对象(如果已经存在 >Address 包含这两个字段(即 unique_together=(address_line1, address_line2))?

最佳答案

最近遇到了类似的问题,采用以下方法解决(代码未经测试,仅供引用):

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)

希望这有帮助:)

关于django - 重用 Django Rest Framework 嵌套序列化器中的现有对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26247192/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com