Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Rest Framework 3.7.7 does not handle Null/None ForeignKey values

I am getting an error with Django Rest Framework when my ForeignKey contains a null value.

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',
        )

Accessing the data attribute of this serializer, when the unit foreign key field is 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'

As you can see, setting allow_null still does not work, and drf seems to be complaining about the NoneType object.

How am I able to fix this error so that I can use null values with drf?

like image 674
juiceb0xk Avatar asked Jan 21 '26 04:01

juiceb0xk


1 Answers

I just upgraded myself and ran into this. Gave it a quick google and found this in the docs:

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.

like image 136
Ben P Avatar answered Jan 23 '26 21:01

Ben P



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!