gpt4 book ai didi

Django Rest Framework 3.7.7 不处理 Null/None ForeignKey 值

转载 作者:行者123 更新时间:2023-12-04 01:57:24 26 4
gpt4 key购买 nike

当我的 ForeignKey 包含空值时,Django Rest Framework 出现错误。

unit = models.ForeignKey(
SubLocation,
on_delete=models.CASCADE,
related_name='unit',
blank=True,
null=True,
)

class AssetSerializer(serializers.ModelSerializer):

unit = serializers.PrimaryKeyRelatedField(
source='unit.name',
allow_null=True,
default=None,
queryset=SubLocation.objects.all(),
)

class Meta:
model = Asset
fields = ('pk', 'unit',
)

访问这个序列化器的数据属性,当unit外键字段为None时

>> ass = Asset.objects.first()
>> AssetSerializer(ass).data

Traceback (most recent call last):
File "<console>", line 1, in <module>
File "C:\Python36\lib\site-packages\rest_framework\serializers.py", line 537, in data
ret = super(Serializer, self).data
File "C:\Python36\lib\site-packages\rest_framework\serializers.py", line 262, in data
self._data = self.to_representation(self.instance)
File "C:\Python36\lib\site-packages\rest_framework\serializers.py", line 491, in to_representation
attribute = field.get_attribute(instance)
File "C:\Python36\lib\site-packages\rest_framework\relations.py", line 177, in get_attribute
return get_attribute(instance, self.source_attrs)
File "C:\Python36\lib\site-packages\rest_framework\fields.py", line 100, in get_attribute
instance = getattr(instance, attr)
AttributeError: 'NoneType' object has no attribute 'unit'

如您所见,设置 allow_null 仍然不起作用,并且 drf 似乎在提示 NoneType 对象。

我怎样才能修复这个错误,以便我可以在 drf 中使用空值?

最佳答案

我刚刚升级自己并遇到了这个。快速谷歌一下,在文档中找到了这个:

When serializing fields with dotted notation, it may be necessary to provide a default value if any object is not present or is empty during attribute traversal.

关于Django Rest Framework 3.7.7 不处理 Null/None ForeignKey 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49673766/

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