I have Char objects with ManyToMany relationships to Source objects. Because a Char can appear in many Sources and many Sources can contain multiple Chars. The MtM relationship goes through a through table which also contains page number. In my API response, which I built using the Django REST framework I want to avoid resolving the full Source title, author etc. for every Char. Rather, in order to reduce the size of the JSON response, I want to refer it by id and include a sources section so the client can look it up.
I.e. a client visiting /api/char/26 should get the following response:
"chars": [
{
"id": 26,
"name": "龜",
"locations": [
{
"page": 136,
"source": 1
},
{
"page": 162,
"source": 1
}
]
}
],
"sources": [
{
"id": 1,
"title": "Bruksanvisning Foamglass",
"author": "Bluppfisk"
}
]
Here's the API view:
class CharAPIView(generics.RetrieveAPIView):
queryset = Char.objects.all()
serializer_class = CharSerializer
and the Serializers:
class CharSerializer(serializers.ModelSerializer):
locations = serializers.SerializerMethodField()
class Meta:
model = Char
fields = ('id', 'name', 'locations',)
depth = 1
def get_locations(self, obj):
qset = CharInSource.objects.filter(char=obj)
return [CharInSourceSerializer(m).data for m in qset]
class CharInSourceSerializer(serializers.ModelSerializer):
class Meta:
model = CharInSource
fields = ('page', 'source',)
The problem is I do not know how to hook into the generics.RetrieveAPIView class so it will include a list of relevant sources. I've been digging through the source, but I cannot figure out how to even get the pk value.