Python:peewee工具函数model_to_dict的用法参数详解

举报
彭世瑜 发表于 2022/09/26 01:06:03 2022/09/26
【摘要】 定义 model_to_dict( model[, recurse=True[, backrefs=False[, only=None[, exclude=None...

定义

model_to_dict(
	model[, 
		recurse=True[, 
			backrefs=False[, 
				only=None[, 
					exclude=None[, 
						extra_attrs=None[, 
							fields_from_query=None[, 
								max_depth=None[, 
									manytomany=False
]]]]]]]])

参数

recurse (bool) – Whether foreign-keys should be recursed.
backrefs (bool) – Whether lists of related objects should be recursed.
only – A list (or set) of field instances which should be included in the result dictionary.
exclude – A list (or set) of field instances which should be excluded from the result dictionary.
extra_attrs – A list of attribute or method names on the instance which should be included in the dictionary.
fields_from_query (Select) – The SelectQuery that created this model instance. Only the fields and values explicitly selected by the query will be serialized.
max_depth (int) – Maximum depth when recursing.
manytomany (bool) – Process many-to-many fields.

示例

模型定义

# -*- coding: utf-8 -*-
import json
from datetime import datetime

from peewee import CharField, IntegerField, DateTimeField, BooleanField, TextField


class UserModel(BaseModel):
    """用户表"""
    id = IntegerField(primary_key=True)

    # 域名
    name = CharField()

    # 密码
    password= CharField(default="")

    # 分组
    age = IntegerField(default=0)

    # 创建时间
    create_time = DateTimeField(default=datetime.now)

    # 更新时间
    update_time = DateTimeField(default=datetime.now)
	
	# 计算属性
    @property
    def username(self):
       return '用户' + self.id
user = UserModel.get_by_id(1)

model_to_dict(
        model=user,
        # 排除密码字段
        exclude=[DomainModel.password],
        # 增加计算属性字段
        extra_attrs=[
            'username'
        ]
    )

参考
https://docs.peewee-orm.com/en/latest/peewee/playhouse.html#model_to_dict
https://github.com/coleifer/peewee/issues/2386

文章来源: pengshiyu.blog.csdn.net,作者:彭世瑜,版权归原作者所有,如需转载,请联系作者。

原文链接:pengshiyu.blog.csdn.net/article/details/127031261

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。