Django REST组外键模型

时间:2017-09-24 06:15:00

标签: python django django-rest-framework

我有类似下面的模型。

菜单型号

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}]
}

谢谢..

1 个答案:

答案 0 :(得分:1)

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

模型

public byte[] openAttach(string id, string code)
    {
        ATTACH_DAL ATT_dal = new ATTACH_DAL();
        ATTACH_Entity ATT_ent = new ATTACH_Entity();

        ATT_ent.PrpATATID = id;
        ATT_ent.PrpATFLNM = code;

        ATT_dal.select_Top_1_ATTACH(ATT_ent, "");

      //here i retrieve the binary data 
        return (byte[])ATT_ent.PrpATSORC;
    }

串行

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')

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

class MenuList(generics.ListAPIView):
    serializer_class = MenuSerializer

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

url.py

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