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

时间:2018-04-05 13:36:18

标签: django django-rest-framework

当我的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外键字段为无

时,访问此序列化程序的数据属性
>> 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一起使用?

1 个答案:

答案 0 :(得分:1)

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

  

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