gpt4 book ai didi

python - Django REST 组外键模型

转载 作者:太空宇宙 更新时间:2023-11-03 14:44:09 25 4
gpt4 key购买 nike

我有如下所示的模型。

菜单模型

class Menu(models.Model):

name = models.CharField(max_length=40, unique=True, verbose_name='menu name')

商品型号

class Item(models.Model):

shop = models.ForeignKey(Shop)
menu = models.ForeignKey(Menu)

name = models.CharField(max_length=500)
price = models.IntegerField(default=0)

我想获取商店 ID 的菜单。

Item.objects.filter(shop_id = 1)

如何按商店 ID 1 的菜单名称对结果进行分组?

示例。

{
menu: menuname1
items: [ {item1}, {item2}]
},
{
menu: menuname2
items: [ {item1}, {item2}]
}

谢谢..

最佳答案

您可以使用嵌套序列化器获得所需的输出,如下所示:

型号

class Item(models.Model):
class Meta:
unique_together = ('shop', 'menu',)

shop = models.ForeignKey(Shop)
menu = models.ForeignKey(Menu, related_name='items')
name = models.CharField(max_length=500)
price = models.IntegerField(default=0)

序列化器

class ItemSerializer(serializers.ModelSerializer):
class Meta:
model = Item
fields = '__all__'

class MenuSerialzer(serializers.ModelSerializer):
items = ItemSerializer(many=True, read_only=True)
class Meta:
model = Menu
fields = ('name','items')

观看次数

class MenuList(generics.ListAPIView):
serializer_class = MenuSerializer

def get_queryset(self):
return Menu.objects.filter(item__shop__id = 1)

我确信你不希望每次都得到 shop_id = 1所以这样做:

class MenuList(generics.ListAPIView):
def get_queryset(self):
shop_id = int(self.kwargs['shop_id'])
return Menu.objects.filter(item__shop__id = 1)

url.py

urlpatterns = [
url('^menus/(?P<shop_id>[0-9]+)/$', MenuList.as_view()),
]

关于python - Django REST 组外键模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46387174/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com