drf-writable-nested
drf-writable-nested copied to clipboard
Nested create ignore to_internal_value method
I need to abstract a nested representation:
// The request body I need
{
"name": "the name",
"topic_type": "the type"
}
instead of
{
"name": "the name",
"topic_type": {
"topic_type": "the type"
}
}
To achieve that, I use these serializers and models :
class TopicType(models.Model):
topic_type = models.CharField(max_length=64)
class Topic(models.Model):
name = models.CharField(max_length=64)
topic_type = models.ForeignKey('TopicType', on_delete=models.CASCADE)
class TopicTypeSerializer(serializers.ModelSerializer):
class Meta:
model = TopicType
fields = ('topic_type',)
def to_representation(self, instance):
return instance.topic_type
def to_internal_value(self, data):
return {'topic_type': data}
def create(self, validated_data):
return TopicType.objects.get_or_create(**validated_data)[0]
class TopicSerializer(WritableNestedModelSerializer):
topic_type = TopicTypeSerializer()
class Meta:
model = Topic
fields = ('name', 'topic_type')
On the line https://github.com/beda-software/drf-writable-nested/blob/master/drf_writable_nested/mixins.py#L174, it uses the initial_data and not the validated_data (so it doesn't use the to_internal_value's return) and crash with
File ".../lib/python3.6/site-packages/drf_writable_nested/mixins.py", line 108, in _get_related_pk
pk = data.get('pk') or data.get(model_class._meta.pk.attname)
AttributeError: 'str' object has no attribute 'get'
My issue seems similar to https://github.com/beda-software/drf-writable-nested/issues/39 It would be nice to be able to customize nested deserialization behavior!
Hello @Amoki! It is impossible to do it now because we always use initial_data
instead of validated_data
. Follow #57, maybe it will add some flexibility in the near future.
Hi @ruscoder. I don't see the reason why you use initial_data
at that point as the data that will effectively be used in the object is validated_data
. Could you please give more details?
With the current implementation, what would be the best way to handle this kind of nested representation?