peewee 关于一些示例笔记

模型

图片表:

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,402评论 6 499
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,377评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,483评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,165评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,176评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,146评论 1 297
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,032评论 3 417
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,896评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,311评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,536评论 2 332
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,696评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,413评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,008评论 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,659评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,815评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,698评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,592评论 2 353

推荐阅读更多精彩内容