【问题标题】:Django Rest Framework 3.7.7 does not handle Null/None ForeignKey valuesDjango Rest Framework 3.7.7 不处理 Null/None ForeignKey 值
【发布时间】:2018-04-05 13:36:18
【问题描述】:

当我的 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 中使用空值?

【问题讨论】:

  • @Alasdair 我 100% 确定数据库中有资产。我的资产的某个字段为无,因为设置了 blank=Truenull=True。这就是它抱怨的原因。但我只是不确定为什么。

标签: django django-rest-framework


【解决方案1】:

我刚刚升级了自己并遇到了这个问题。给它一个快速的谷歌并在文档中找到了这个:

使用点分符号序列化字段时,如果在属性遍历期间任何对象不存在或为空,则可能需要提供默认值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-03
    • 2019-02-20
    • 2011-03-30
    • 1970-01-01
    • 2016-12-29
    • 1970-01-01
    • 1970-01-01
    • 2020-06-10
    相关资源
    最近更新 更多