Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

pydantic_model_creator No ForeignKeyField returned #1726

Open
elkon028 opened this issue Oct 2, 2024 · 1 comment
Open

pydantic_model_creator No ForeignKeyField returned #1726

elkon028 opened this issue Oct 2, 2024 · 1 comment
Labels
pydantic Issue related to tortoise.contrib.pydantic

Comments

@elkon028
Copy link

elkon028 commented Oct 2, 2024

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??

@henadzit
Copy link
Contributor

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

@henadzit henadzit added the pydantic Issue related to tortoise.contrib.pydantic label Nov 28, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
pydantic Issue related to tortoise.contrib.pydantic
Projects
None yet
Development

No branches or pull requests

2 participants