I am hitting a KeyError for 'children' when I run this create() function:
class TaskViewSet(ModelViewSet):
queryset = Task.objects.all()
serializer_class = TaskSerializer
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
...
if serializer.is_valid(raise_exception=True):
inputs = serializer.data // KeyError triggers on this line
This is where it is defined in the models:
class Task(models.Model):
...
parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children')
And in my serializer:
class TaskSerializer(serializers.ModelSerializer):
...
children = serializers.PrimaryKeyRelatedField(read_only=True, many=True, required=False, default=[])
class Meta:
model = Task
fields = [
..., 'children',
]
The last few lines of the error:
File "/Users/adamstarrh/opt/anaconda3/envs/onit/lib/python3.9/site-packages/rest_framework/fields.py", line 95, in get_attribute
instance = instance[attr]
KeyError: 'children'
I've set required to false and read_only to true in the serializer, and null to true in the models. What have I missed?
I bypassed this issue by using the serializer's
validated_datainstead: