gpt4 book ai didi

python - AttributeError - 使用 Django NestedFields 序列化器时

转载 作者:太空宇宙 更新时间:2023-11-03 14:36:00 25 4
gpt4 key购买 nike

我有 2 个型号:-

class Users(models.Model):
first_name = models.CharField(max_length=255)
middle_name = models.CharField(max_length=255)


class UserAddress(models.Model):
line1 = models.CharField(max_length=255)
country = models.CharField(max_length=255)
user = models.ForeignKey(Users)

用户模型和用户地址模型。以下是 2 个序列化器。

class UserAddressSerializer(ModelSerializer):

class Meta:
model = UserAddress
exclude = ('id', 'user')


class UserSerializer(ModelSerializer):
address = UserAddressSerializer(many=True)

class Meta:
model = Users
fields = '__all__'

def create(self, validated_data):
address = validated_data.pop('address', [])
user = Users.objects.create(**validated_data)

for ad in address:
UserAddress.objects.create(user=user, **ad)

return user

我从客户端收到的数据是

{
"first_name": "string",
"last_name": "string",
"address": [{
"line1": "asd",
"country": "asd",
}],
}

这就是我创建新用户及其相应地址的方法。

class UserCreate(GenericAPIView):

serializer_class = UserSerializer

def post(self, request, *args, **kwargs):

data = request.data
serializer = UserSerializer(data=data)
if not serializer.is_valid():
return

user = serializer.save()
response = {
'user_id': user.uuid
}
return

现在,在取回用户详细信息后,我收到一条错误消息

AttributeError: Got AttributeError when attempting to get a value for field `address` on serializer `UserSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `Users` instance.
Original exception text was: 'Users' object has no attribute 'address'.

这就是我获取用户详细信息(包括地址)的方法。

class UserDetails(GenericAPIView):
queryset = Users.objects.all()
serializer_class = UserSerializer
lookup_field = 'uuid'

def get(self, request, uuid, *args, **kwargs):
user = Users.get_user(uuid)
if not user:
return

serializer = UserSerializer(instance=user)
return

我读过this example嵌套关系,并且我正在以完全相同的方式进行。为什么会出现错误?

此外,可以使用一些 DRF mixin 来进一步缩短此代码(以更干净的方式)吗?如果是,那么如何?

最佳答案

我认为适合您的情况的最简单的解决方案是:在模型 UserAddress 中添加 lated_name='address'

class UserAddress(models.Model):
line1 = models.CharField(max_length=255)
country = models.CharField(max_length=255)
user = models.ForeignKey(Users, related_name='address')
# ^^^^^^^^^^^^^^^

或者您可以在序列化程序中添加源属性:

class UserSerializer(ModelSerializer):
address = UserAddressSerializer(source='useraddress_set', many=True)

序列化器尝试在模型User中查找属性“address”,但默认情况下它是模型名称下划线集(在您的情况下是useraddress_set),并且您尝试其他名称,因此您可以在模型中设置或通过源指定。

在示例中您可以查看 models并找到lated_name='tracks'

关于python - AttributeError - 使用 Django NestedFields 序列化器时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46947722/

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