如何在一个菜单显示两种数据

发布于 2022-05-06 19:30:12

我有两种django的model他们有部分字段是一样的, 还有部分是每个model独有的, 我想在列表请求数据是返回两种model,在列表显示公共信息, 然后在添加或查看分别显示对应的表单.

查看更多

关注者
0
被浏览
592
hongzai
hongzai 认证专家 2022-05-06
life is coding,外包,远程协助,咨询添加微信:H0nGzA1

你可以在crud里添加共同的字段,在序列化时用serializerMethod字段动态返回数据,或者用to_representation方法返回更多属性,这两种方式都能够实现返回更多的数据,不只是你的表里的字段,也没有表的限制,也可以是其他表,like this
image.png
image.png

class DockingModelSerializer(CustomModelSerializer):
    """
    序列化器
    """

    # oid = serializers.SerializerMethodField()  # 订单ID
    # itemId = serializers.SerializerMethodField()  # 商品ID
    # itemImgUrl = serializers.SerializerMethodField()  # 商品图
    # itemTitle = serializers.SerializerMethodField()  # 商品标题
    # itemPrice = serializers.SerializerMethodField()  # 商品价格
    # cpsOrderStatus = serializers.SerializerMethodField()  # 订单状态

    # def get_oid(self, obj):
    #     return OrderModel.objects.get(itemId=obj.itemId).oid

    # def get_itemImgUrl(self, obj):
    #     print(GoodsModel.objects.get(itemId=obj.itemId))
    #     return 'test'
    #
    # def get_itemTitle(self, obj):
    #     return GoodsModel.objects.get(itemId=obj.itemId).itemTitle
    #
    # def get_itemPrice(self, obj):
    #     return GoodsModel.objects.get(itemId=obj.itemId).itemPrice
    #
    # def get_cpsOrderStatus(self, obj):
    #     return GoodsModel.objects.get(itemId=obj.itemId).cpsOrderStatus

    sales = serializers.SerializerMethodField()  # 销量
    regimentalPromotionAmount = serializers.SerializerMethodField()  # 预估

    def get_sales(self, obj):
        return GoodsModel.objects.filter(itemId=obj.itemId).count()

    def get_regimentalPromotionAmount(self, obj):
        return round(random.random(), 2)

    def to_representation(self, instance):
        data = super().to_representation(instance)
        if OrderModel.objects.filter(itemId=instance.itemId).exists():
            data['oid'] = OrderModel.objects.filter(itemId=instance.itemId)[0].oid
        else:
            data['oid'] = ''
        data['itemImgUrl'] = GoodsModel.objects.filter(itemId=instance.itemId)[0].itemImgUrl
        data['itemTitle'] = GoodsModel.objects.filter(itemId=instance.itemId)[0].itemTitle
        data['itemPrice'] = GoodsModel.objects.filter(itemId=instance.itemId)[0].itemPrice / 100
        data['itemStatus'] = GoodsModel.objects.filter(itemId=instance.itemId)[0].get_itemStatus_display()
        data['itemAuditStatus'] = GoodsModel.objects.filter(itemId=instance.itemId)[0].get_itemAuditStatus_display()
        data['itemStock'] = GoodsModel.objects.filter(itemId=instance.itemId)[0].itemStock
        return data

    class Meta:
        model = DockingModel
        fields = "__all__"
2 个回答
xingshuyin
xingshuyin 2022-05-07
This guy hasn't written anything yet

.

撰写答案

请登录后再发布答案,点击登录

发布
问题

分享
好友

手机
浏览

扫码手机浏览