我的模型如下所示:
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()
我想做的是在给定的 MenuItem 中公开一个包含 isReplaceable 字段的组件列表(不是 MenuItemComponents)。到目前为止,我有:
#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
它公开了一个 MenuItemComponents 列表并强制客户端进行多次调用以检索所有组件。使用 isReplaceable 字段中的附加数据公开组件列表将解决问题。
编辑
最后,我想获得一个列出 Component 元素的列表,但这些元素是用 MenuItemComponent 模型中的 isReplaceable 字段扩展的:
{
"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
}
]
}