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

定义

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

猜你喜欢

转载自blog.csdn.net/mouday/article/details/127031261
今日推荐