tortoise/tortoise-orm

pydantic_model_creator No ForeignKeyField returned

elkon028 opened this issue · 2 comments

Describe the bug

class DeptModel(Model):
    name = fields.CharField(max_length=50, description='部门名称')
    sort = fields.SmallIntField(default=0, description='排序')
    leader = fields.CharField(max_length=30, default=None, null=True, description='负责人')
    phone = fields.CharField(max_length=30, default=None, null=True, description='手机')
    email = fields.CharField(max_length=50, default=None, null=True, description='邮箱')
    status = fields.BooleanField(default=True, description='部门状态')

    parent: fields.ForeignKeyNullableRelation['DeptModel'] = fields.ForeignKeyField(
        'models.DeptModel',
        null=True,
        related_name='children',
        description='父级部门',
        on_delete=fields.CASCADE,
    )

    children: fields.ReverseRelation['DeptModel']

    class Meta:
        table = 'sys_dept'
        table_description = '部门'
        ordering = ['parent_id', '-sort']


DeptOut = pydantic_model_creator(
    DeptModel,
    name='DeptOut',
    allow_cycles=True,
    model_config=modelOutConfig,
)

@router.get('/{pk}', summary='获取部门信息')
async def info(pk: Annotated[int, Path(...)]):
    dept = await DeptOut.from_tortoise_orm(await DeptModel.get_or_none(id=pk))
    return dept.model_dump()

returned

{
    "id": 13,
    "name": "部门2",
    "sort": 0,
    "leader": null,
    "phone": null,
    "email": null,
    "status": true
}

Why hasn't the parent_id been returned??

@elkon028 have you initialized tortoise models? You might need to do early model init BEFORE you create Pydantic schemas.