美文网首页
peewee 关于一些示例笔记

peewee 关于一些示例笔记

作者: 小钟钟同学 | 来源:发表于2019-04-02 13:08 被阅读0次

    模型

    图片表:

    class FloweshopImages(BaseModel):
        ctime = DateTimeField(constraints=[SQL("DEFAULT now()")], null=True)
        name = TextField(constraints=[SQL("DEFAULT ''::text")], index=True)
        path = TextField(constraints=[SQL("DEFAULT ''::text")], null=True)
        url = TextField(constraints=[SQL("DEFAULT ''::text")], index=True)
        utime = DateTimeField(constraints=[SQL("DEFAULT now()")], null=True)
    
        class Meta:
            table_name = 'floweshop_images'
    

    商品图片表集:

    class FloweshopGoodsImages(BaseModel):
        ctime = DateTimeField(constraints=[SQL("DEFAULT now()")], null=True)
        goods_id = TextField(column_name='goods_id', constraints=[SQL("DEFAULT ''::text")], index=True, null=True)
        images_id = IntegerField(column_name='images_id', index=True, null=True)
        sort = IntegerField(constraints=[SQL("DEFAULT 0")], null=True)
        type = IntegerField(null=True)
    
        class Meta:
            table_name = 'floweshop_goods_images'
    

    商品款式表

    class FloweshopGoodsStyle(BaseModel):
        ctime = DateTimeField(constraints=[SQL("DEFAULT now()")], null=True)
        ctprice = DecimalField(null=True)
        goods_id = TextField(column_name='goods_id', constraints=[SQL("DEFAULT ''::text")], index=True, null=True)
        mktprice = DecimalField(null=True)
        name = TextField(constraints=[SQL("DEFAULT ''::text")], index=True, null=True)
        sbprice = DecimalField(null=True)
        utime = DateTimeField(constraints=[SQL("DEFAULT now()")], null=True)
    
        class Meta:
            table_name = 'floweshop_goods_style'
    

    商品表:

    
    class FloweshopGoods(BaseModel):
        attribute_id = TextField(column_name='attribute_id', constraints=[SQL("DEFAULT ''::text")], index=True, null=True)
        bn = TextField(constraints=[SQL("DEFAULT ''::text")], index=True)
        brand = TextField(column_name='brand_id', constraints=[SQL("DEFAULT '00000'::text")], index=True, null=True)
        buy_count = IntegerField(null=True)
        comments_count = IntegerField(constraints=[SQL("DEFAULT 0")], null=True)
        ctime = DateTimeField(constraints=[SQL("DEFAULT now()")], null=True)
        ctprice = DecimalField(null=True)
        des_selling_point = TextField(constraints=[SQL("DEFAULT ''::text")], null=True)
        describe = TextField(constraints=[SQL("DEFAULT ''::text")], null=True)
        downmarkettime = DateTimeField(null=True)
        freeze_stock = IntegerField(null=True)
        goods_cat_id = TextField(column_name='goods_cat_id', constraints=[SQL("DEFAULT ''::text")], index=True, null=True)
        goods_type_id = TextField(column_name='goods_type_id', constraints=[SQL("DEFAULT ''::text")], index=True, null=True)
        # image_id = TextField(column_name='image_id', constraints=[SQL("DEFAULT ''::text")], null=True)
        image_id = IntegerField(null=True)
        image_intro_id = TextField(column_name='image_intro_id', constraints=[SQL("DEFAULT ''::text")], index=True, null=True)
        is_hot = IntegerField(index=True, null=True)
        is_in_marketable = IntegerField(null=True)
        is_nomal_virtual = IntegerField(null=True)
        is_promotion = IntegerField(index=True, null=True)
        is_recommend = IntegerField(index=True, null=True)
        label_ids = TextField(constraints=[SQL("DEFAULT ''::text")], null=True)
        mktprice = DecimalField(null=True)
        name = TextField(constraints=[SQL("DEFAULT ''::text")], index=True)
        params = TextField(constraints=[SQL("DEFAULT ''::text")], null=True)
        price_range = TextField(constraints=[SQL("DEFAULT ''::text")], null=True)
        remark = TextField(constraints=[SQL("DEFAULT ''::text")], null=True)
        sbprice = DecimalField(null=True)
        sort = IntegerField(constraints=[SQL("DEFAULT 0")], index=True, null=True)
        stock = IntegerField(null=True)
        style_id = TextField(column_name='style_id', constraints=[SQL("DEFAULT ''::text")], index=True, null=True)
        unit = TextField(constraints=[SQL("DEFAULT ''::text")], null=True)
        upmarkettime = DateTimeField(null=True)
        utime = DateTimeField(constraints=[SQL("DEFAULT now()")], null=True)
        view_count = IntegerField(constraints=[SQL("DEFAULT 0")], null=True)
        weight = TextField(constraints=[SQL("DEFAULT ''::text")], null=True)
        wx_share_des = TextField(constraints=[SQL("DEFAULT ''::text")], null=True)
    
        class Meta:
            table_name = 'floweshop_goods'
    

    添加测试数据:

    
        # 添加图片表的记录
        FloweshopImages(name='商品1图片', url='http://ysj.iread.wo.com.cn/ysjpic/res/ysjzengguofansy.jpg?v=0dYiV', path='').save()
        FloweshopImages(name='商品1图片', url='http://ysj.iread.wo.com.cn/ysjpic/res/caijunbn.png?v=erwLX', path='').save()
        FloweshopImages(name='商品1图片', url='http://ysj.iread.wo.com.cn/ysjpic/res/qianlaoshisp.jpg?v=xkNne', path='').save()
        FloweshopImages(name='商品1介绍', url='http://ysj.iread.wo.com.cn/ysjpic/res/qianlaoshisp.jpg?v=xkNne', path='').save()
        FloweshopImages(name='商品1介绍', url='http://ysj.iread.wo.com.cn/ysjpic/res/qianlaoshisp.jpg?v=xkNne', path='').save()
        FloweshopImages(name='商品2介绍', url='http://ysj.iread.wo.com.cn/ysjpic/res/qianlaoshisp.jpg?v=xkNne', path='').save()
        FloweshopImages(name='商品3介绍', url='http://ysj.iread.wo.com.cn/ysjpic/res/qianlaoshisp.jpg?v=xkNne', path='').save()
    
    
        # 添加商品图片表
        FloweshopGoodsImages(images_id=1, goods_id='gc100010', type='1').save()
        FloweshopGoodsImages(images_id=2, goods_id='gc100011', type='1').save()
        FloweshopGoodsImages(images_id=2, goods_id='gc100012', type='1').save()
    
    
        # 商品表
        FloweshopGoods(bn='gc100010', name='商品1', describe='商品介绍文字描述', des_selling_point='商品简介卖点描述', wx_share_des='微信分享时候的显示的描述', ctprice=345.34,
                       mktprice=55854.54, sbprice=56.55, price_range='2342~324', image_id='3,4', goods_cat_id=1, goods_type_id=1, is_nomal_virtual=1, is_in_marketable=2, stock=100,
                       freeze_stock=0, image_intro_id='34,45,345', attribute_id='1,2,3', style_id='1,2,3').save()
    
        # 商品表image_id---后续修改为int类型
        FloweshopGoods(bn='gc100011', name='商品2', describe='商品介绍文字描述', des_selling_point='商品简介卖点描述', wx_share_des='微信分享时候的显示的描述', ctprice=345.34,
                       mktprice=55854.54, sbprice=56.55, price_range='2342~324', image_id='5', goods_cat_id=2, goods_type_id=2, is_nomal_virtual=1, is_in_marketable=2, stock=100,
                       freeze_stock=0, image_intro_id='34,45,345', attribute_id='1,2,3', style_id='3,5').save()
    
        # 商品表image_id---后续修改为int类型
        FloweshopGoods(bn='gc100011', name='商品2', describe='商品介绍文字描述', des_selling_point='商品简介卖点描述', wx_share_des='微信分享时候的显示的描述', ctprice=345.34,
                       mktprice=55854.54, sbprice=56.55, price_range='2342~324', image_id='6', goods_cat_id=2, goods_type_id=2, is_nomal_virtual=1, is_in_marketable=2, stock=100,
                       freeze_stock=0, image_intro_id='34,45,345', attribute_id='1,2,3', style_id='3,5').save()
    

    示例需求:

    1:查询所有的商品列表下的对应的图片

    使用点:
    1:使用了dicts()和没使用dicts()的有很大的区别
    2:连表中有相同的字段重名的重新命名alias的使用

    query1 = FloweshopGoods.select(FloweshopGoodsImages.images_id.alias('图片XXX'), FloweshopGoodsImages.goods_id, FloweshopImages.name.alias('XXXXXXXXXXXX'), FloweshopGoods).join(FloweshopGoodsImages, on=(
            FloweshopGoodsImages.images_id == FloweshopGoods.image_id)) \
        .join(FloweshopImages, on=(FloweshopGoodsImages.images_id == FloweshopImages.id)).dicts()
    

    查询的结果为:

    ============查询结果==============
    {'upmarkettime': None, 'stock': 100, 'goods_type_id': '1', 'wx_share_des': '微信分享时候的显示的描述', 'XXXXXXXXXXXX': '商品1图片', 'brand': '00000', 'is_nomal_virtual': 1, 'style_id': '1,2,3', 'attribute_id': '1,2,3', 'mktprice': Decimal('55854.54'), 'ctime': datetime.datetime(2019, 3, 29, 18, 33, 14), 'name': '商品1', 'id': 1, 'sbprice': Decimal('56.55'), 'ctprice': Decimal('345.34'), '图片XXX': 1, 'unit': '', 'image_intro_id': '34,45,345', 'buy_count': None, 'describe': '商品介绍文字描述', 'weight': '', 'is_recommend': None, 'downmarkettime': None, 'image_id': 1, 'price_range': '2342~324', 'sort': 0, 'des_selling_point': '商品简介卖点描述', 'is_promotion': None, 'label_ids': '', 'utime': datetime.datetime(2019, 3, 29, 18, 33, 14), 'remark': '', 'goods_id': 'gc100010', 'freeze_stock': 0, 'comments_count': 0, 'bn': 'gc100010', 'view_count': 0, 'is_in_marketable': 2, 'goods_cat_id': '1', 'is_hot': None, 'params': ''}
    {'upmarkettime': None, 'stock': 100, 'goods_type_id': '2', 'wx_share_des': '微信分享时候的显示的描述', 'XXXXXXXXXXXX': '商品1图片', 'brand': '00000', 'is_nomal_virtual': 1, 'style_id': '3,5', 'attribute_id': '1,2,3', 'mktprice': Decimal('55854.54'), 'ctime': datetime.datetime(2019, 3, 29, 18, 33, 14), 'name': '商品2', 'id': 2, 'sbprice': Decimal('56.55'), 'ctprice': Decimal('345.34'), '图片XXX': 2, 'unit': '', 'image_intro_id': '34,45,345', 'buy_count': None, 'describe': '商品介绍文字描述', 'weight': '', 'is_recommend': None, 'downmarkettime': None, 'image_id': 2, 'price_range': '2342~324', 'sort': 0, 'des_selling_point': '商品简介卖点描述', 'is_promotion': None, 'label_ids': '', 'utime': datetime.datetime(2019, 3, 29, 18, 33, 14), 'remark': '', 'goods_id': 'gc100011', 'freeze_stock': 0, 'comments_count': 0, 'bn': 'gc100011', 'view_count': 0, 'is_in_marketable': 2, 'goods_cat_id': '2', 'is_hot': None, 'params': ''}
    {'upmarkettime': None, 'stock': 100, 'goods_type_id': '2', 'wx_share_des': '微信分享时候的显示的描述', 'XXXXXXXXXXXX': '商品3介绍', 'brand': '00000', 'is_nomal_virtual': 1, 'style_id': '3,5', 'attribute_id': '1,2,3', 'mktprice': Decimal('55854.54'), 'ctime': datetime.datetime(2019, 3, 29, 18, 33, 14), 'name': '商品2', 'id': 3, 'sbprice': Decimal('56.55'), 'ctprice': Decimal('345.34'), '图片XXX': 7, 'unit': '', 'image_intro_id': '34,45,345', 'buy_count': None, 'describe': '商品介绍文字描述', 'weight': '', 'is_recommend': None, 'downmarkettime': None, 'image_id': 7, 'price_range': '2342~324', 'sort': 0, 'des_selling_point': '商品简介卖点描述', 'is_promotion': None, 'label_ids': '', 'utime': datetime.datetime(2019, 3, 29, 18, 33, 14), 'remark': '', 'goods_id': 'gc100012', 'freeze_stock': 0, 'comments_count': 0, 'bn': 'gc100011', 'view_count': 0, 'is_in_marketable': 2, 'goods_cat_id': '2', 'is_hot': None, 'params': ''}
    
    

    2:查询所有的指定商品下对应的款式列表(注意没有使用dicts())

    query1 = FloweshopGoods.select(FloweshopGoods, FloweshopGoodsStyle).join(FloweshopGoodsStyle, on=(
            FloweshopGoodsStyle.goods_id == FloweshopGoods.bn)).where(FloweshopGoods.bn == 'gc100010')
    
    # 查询出
    from basic.utils.json import json_helper
    # 查询出
    for v in query1:
        print(dir(v))
        print(json_helper.class_to_dict(v.floweshopgoodsstyle))
    # result_list = [v for v in query1]  # 使用列表推导式?
    # print(result_list)
    

    结果:

    =====查询款式=====================
    {'ctime': datetime.datetime(2019, 3, 29, 18, 36, 32), 'goods_id': 'gc100010', 'mktprice': Decimal('122.99'), 'name': '玫瑰之约', 'ctprice': Decimal('222.99'), 'id': 1, 'sbprice': Decimal('4534.56'), 'utime': datetime.datetime(2019, 3, 29, 18, 36, 32)}
    {'ctime': datetime.datetime(2019, 3, 29, 18, 36, 32), 'goods_id': 'gc100010', 'mktprice': Decimal('122.99'), 'name': '爱上之约', 'ctprice': Decimal('222.99'), 'id': 2, 'sbprice': Decimal('4534.56'), 'utime': datetime.datetime(2019, 3, 29, 18, 36, 32)}
    {'ctime': datetime.datetime(2019, 3, 29, 18, 36, 32), 'goods_id': 'gc100010', 'mktprice': Decimal('122.99'), 'name': '345之约', 'ctprice': Decimal('222.99'), 'id': 3, 'sbprice': Decimal('4534.56'), 'utime': datetime.datetime(2019, 3, 29, 18, 36, 32)}
    
    

    3:查询所有的指定商品下对应的款式列表(注意没有使用dicts())

    print('=====查询款式=====================')
    query1 = FloweshopGoodsStyle.select( FloweshopGoodsStyle).join(FloweshopGoods, on=(
            FloweshopGoodsStyle.goods_id == FloweshopGoods.bn)).where(FloweshopGoods.bn == 'gc100010')
    for v in query1:
        # print(dir(v))
        print(json_helper.class_to_dict(v))
        # print(json_helper.dict_to_json(json_helper.class_to_dict(v)))
        # print(json_helper.class_to_dict(v.floweshopgoodsstyle))
    

    没有使用dicts()的情况下,连表的时候包含有自定义的属性字段的时候,会无法查询出对于的记录:

    image.png

    取消 的情况下可以 :

    image.png image.png

    结果:

    {'utime': datetime.datetime(2019, 3, 29, 18, 36, 32), 'sbprice': Decimal('4534.56'), 'ctime': datetime.datetime(2019, 3, 29, 18, 36, 32), 'ctprice': Decimal('222.99'), 'name': '玫瑰之约', 'id': 1, 'goods_id': 'gc100010', 'mktprice': Decimal('122.99')}
    {'utime': datetime.datetime(2019, 3, 29, 18, 36, 32), 'sbprice': Decimal('4534.56'), 'ctime': datetime.datetime(2019, 3, 29, 18, 36, 32), 'ctprice': Decimal('222.99'), 'name': '爱上之约', 'id': 2, 'goods_id': 'gc100010', 'mktprice': Decimal('122.99')}
    {'utime': datetime.datetime(2019, 3, 29, 18, 36, 32), 'sbprice': Decimal('4534.56'), 'ctime': datetime.datetime(2019, 3, 29, 18, 36, 32), 'ctprice': Decimal('222.99'), 'name': '345之约', 'id': 3, 'goods_id': 'gc100010', 'mktprice': Decimal('122.99')}
    

    关于peewee更新的可以给予Mode形式也可以基于的字典的形式进行更新:

    q = Person.update({
        'height': 1.75
    }).where(Person.name == 'Jack')
    q.execute()
    

    # 根据Appid获取一个模型
    # def get_mode_cp_partners_and_product_info(appid='', membershipid=''):
    #     cache_key = 'xmly_directcharge_cp_partners:' + str(appid)
    #     # 获取缓存值
    #     result = redis_cache_helper.get(cache_key)
    #     # 判断是否有值
    #     if result:
    #         return result
    #     # 数据库中读取
    #     with session_scope():
    #         # 说明.get_or_none
    #         # ,select()
    #         # 函数里面需要写上自己需要的返回值,否则联表之后会发现竟然还是只有自己
    #         # cls
    #         # 的字段,就会感觉到很疑惑。
    #         result = CpPartners \
    #             .select(CpPartners,
    #                     ProductInfo.goodsname,
    #                     ProductInfo.time_expire,
    #                     ProductInfo.membershipid,
    #                     ProductInfo.membership_name,
    #                     ProductInfo.valid_days,
    #                     ProductInfo.price,
    #                     ProductInfo.total_fee
    #                     ) \
    #             .join(ProductInfo, on=(CpPartners.appid == ProductInfo.appid)).where((CpPartners.appid == appid) & (ProductInfo.membershipid == membershipid)).dicts().get()
    #             # .join(ProductInfo, on=(CpPartners.appid == ProductInfo.appid)).where(CpPartners.appid == appid).dicts().get()
    #
    #
    #         if result:
    #             # 注意事项,如果不直接的转dicts,那么需要使用的下面的方式进行 融合
    #             # print(result.wxpartners)
    #             # result_cppartners = json_helper.class_to_dict(result)
    #             # result_wxpartners = json_helper.class_to_dict(result.wxpartners)
    #             # # 合并两个字典
    #             # result = dict(result_cppartners, **result_wxpartners)
    #             # 把对应的结果保存到缓存中-时间超时 60*60=一个小时 --10天后过期
    #             redis_cache_helper.set(cache_key, result, timeout=60 * 60 * 24 * 10)
    #         return result
    

    关于PEEWEE 分组统计和 按小时统计

    表结果:

    class TelephoneRechargeInfo(BaseModel):
        amount = TextField(null=True)
        appid = TextField(constraints=[SQL("DEFAULT ''::text")], index=True, null=True)
        channeid = TextField(null=True)
        end_time = DateTimeField(null=True)
        membership_name = TextField(null=True)
        membershipid = TextField(null=True)
        mobile = TextField(constraints=[SQL("DEFAULT ''::text")], index=True, null=True)
        out_trade_no = TextField(constraints=[SQL("DEFAULT ''::text")], index=True, null=True)
        remark = TextField(constraints=[SQL("DEFAULT ''::text")], null=True)
        retrun_code = TextField(constraints=[SQL("DEFAULT ''::text")], null=True)
        retrun_descript = TextField(constraints=[SQL("DEFAULT ''::text")], null=True)
        retrun_innercode = TextField(constraints=[SQL("DEFAULT ''::text")], null=True)
        retrun_result = TextField(constraints=[SQL("DEFAULT ''::text")], null=True)
        send_time = DateTimeField(null=True)
        start_time = DateTimeField(index=True, null=True)
        state = IntegerField(constraints=[SQL("DEFAULT 0")], index=True, null=True)
        taskid = TextField(constraints=[SQL("DEFAULT ''::text")], null=True)
    
        class Meta:
            table_name = 'telephone_recharge_info'
    
    

    分组统计SQL查询语句为:

    SELECT to_char(send_time, 'HH24') as d,COUNT(id) as total_countl FROM telephone_recharge_info WHERE send_time>'2019-08-02 10:14:09' GROUP BY d ORDER BY d;
    

    使用PEEWEE实现的方式为:

        print(TaskTelephoneRechargeInfo.select(TaskTelephoneRechargeInfo.send_time.hour.alias('小时'),fn.COUNT(TaskTelephoneRechargeInfo.id))
             .where((TaskTelephoneRechargeInfo.send_time > '2019-08-02 10:14:09')).group_by(TaskTelephoneRechargeInfo.send_time.hour).order_by(TaskTelephoneRechargeInfo.send_time.hour))
    
    打印出来的sQL语句为:
    SELECT EXTRACT('hour' FROM "t1"."send_time") AS "小时", COUNT("t1"."id") FROM "telephone_recharge_info" AS "t1" WHERE ("t1"."send_time" > '2019-08-02 10:14:09') GROUP BY EXTRACT('hour' FROM "t1"."send_time") ORDER BY EXTRACT('hour' FROM "t1"."send_time")
    
    

    相关文章

      网友评论

          本文标题:peewee 关于一些示例笔记

          本文链接:https://www.haomeiwen.com/subject/lsdwbqtx.html