Skip to content

async nested model pydantic property #3084

@panla

Description

@panla

question

  • fastapi
  • tortoise-orm
  • pydantic
# models
from tortoise import fields
from tortoise.models import Model

class User(Model):
    cellphone = fields.CharField(max_length=16, null=False, unique=True)
    ...

class Question(Model):
    owner_id = fields.BigIntField(index=True)
    ...

    @property
    async def owner(self):
        ...
        return User.get_or_none(id=self.id)

# schema
class OwnerBaseField(BaseModel):
    id: int
    cellphone: str

class QuestionBaseField(BaseModel):
    ...
    owner: Optional[OwnerBaseField]

# api
@router.get('/{q_id}', response_model=QuestionBaseField)
async def read_question(q_id):
    question = await Question.get_or_none(id=q_id)
    return question

to get async property function in pydantic model

question.owner = await question.owner_ is not a good idea, no foreignkey

are there some better ideas?

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions