I have a fairly niche use case that I'm trying to use DRF serializers for. It will be hard to explain precisely what I'm doing, or why I'm doing it, but I need it to work like this.
I have a ModelSerializer, that has nested in it, a regular Serializer, and another ModelSerializer. Something like this:
class ASerializer(Serializer):
...some fields
class BSerializer(ModelSerializer):
class Meta:
model = Foo
fields = '__all__'
class CSerializer(ModelSerializer):
a = ASerializer()
b = BSerializer(source='*')
class Meta:
model = Foo
fields = ('a', ' b')
I want to use it like this:
s = CSerializer(foo_instance, data={'a': ...some data})
s.is_valid() # if necessary
out_data = s.data
Expecting:
out_data = {'a': ...some manipulated data, 'b': ...the serialized foo instance}
So I want to have a serializer, that I pass an instance of Foo to, and some data. The instance of foo is simply to be passed to the nested ModelSerializer (BSerializer) to serialize back out (in a very specific way), and the data I pass is just for the nested Serializer (ASerializer) for that to do some logic (possibly validation) on, and send back out. I'm not using this to modify the model instance in any way, at no point will I call save/create/whatever. It's basically just a data transformation leveraging DRF serializers.
The issue I have is that after initialization, and validation (which does pass!) I get the error:
Got AttributeError when attempting to get a value for field `a` on serializer `CSerializer` ... Original exception text was: 'Foo' object has no attribute 'a'
I also appreciate that the following works without error:
x = ASerializer(data=...some data)
x.is_valid()
y = BSerializer(foo_instance)
out_data = {'a': x.data, 'b': y.data}
But it seems like my desired interface, combining these steps by a single serializer, should be possible - but I can't figure it out.