I'm using Django Rest Framework to write my API. I want to write different values than the the id (specifically the uuid) into my serializer.
Let me give you the basic setup first. I have a model called House
which has amongst other values a pk and a uuid. And I have a second model called Citizen
which also has a pk and a uuid. House
and Citizen
have a ManyToMany relationship with each other.
I would like to have a serializer that just gives back an array of it's citizen.
Here is the not working pseudo code that I tried (and failed):
class HouseSerializer(serializers.ModelSerializer):
address = AddressSerializer()
citizen = serializers.UUIDField(source="citizen.uuid")
class Meta:
model = Table
fields = [
"uuid",
"address",
"citizen",
...
]
This serializer throws the error:
AttributeError: Got AttributeError when attempting to get a value for field `citizen` on serializer `HouseListSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `House` instance.
Original exception text was: 'ManyRelatedManager' object has no attribute 'uuid'.
But on my model for the House
I have explicitly citizen = models.ManyToManyField(Citizen)
.
If I just don't specify any serializer and just leave citizen in the fields array, I just get an array of the PKs which I can't use.
How can I get an array of the UUIDs here?