My model looks like this:
class MenuItem(models.Model):
name = models.CharField(max_length=500)
components = models.ManyToManyField(Component, through=MenuItemComponent)
class Component(models.Model):
name = models.CharField(max_length=500)
class MenuItemComponent(models.Model):
menuItem = models.ForeignKey('MenuItem')
component = models.ForeignKey(Component)
isReplaceable = models.BooleanField()
What I'd like to do is expose a list of Components (NOT MenuItemComponents) in given MenuItem that would include the isReplaceable field. So far I have:
#views.py
class MenuItemComponentList(generics.ListAPIView):
"""
Displays components for given MenuItem
"""
model = MenuItemComponent
serializer_class = MenuItemComponentSerializer
def get_queryset(self):
itemId = self.kwargs['itemId']
return MenuItemComponent.objects.filter(menuItem__pk=itemId)
#serializers.py
class MenuItemComponentSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = MenuItemComponent
Which exposes a list of MenuItemComponents and forces clients to make multiple calls in order to retrieve all Components. Exposing Components list with additional data from isReplaceable field would solve the problem.
EDIT
In the end I'd like to get a list that lists Component elements but the elements are exteded with isReplaceable field from MenuItemComponent model:
{
"count": 2,
"next": null,
"previous": null,
"results": [
{
"url": "http://localhost:8000/api/component/1/",
"name": "component 1",
"isReplaceable": true
},
{
"url": "http://localhost:8000/api/component/2/",
"name": "component 2",
"isReplaceable": false
}
]
}