我的模型看起来是这样的:
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()
我想要做的就是将组件暴露在给定的菜单项列表(NOT MenuItemComponents),将包括isReplaceable领域。 到目前为止,我有:
#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领域的其他数据可以解决这个问题。
编辑
最后,我想获得列出构成要素,但要素与MenuItemComponent模型isReplaceable场均exteded列表:
{
"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
}
]
}