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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With