tortoise-orm icon indicating copy to clipboard operation
tortoise-orm copied to clipboard

help,pydantic_model_creator con't display to reponse_model output foreignkey_value.

Open Mecil9 opened this issue 3 years ago • 4 comments

models.py:

class PostCategory(Model):
    """category model"""
    id = fields.IntField(pk=True)
    name = fields.CharField(max_length=50)
    published = fields.BooleanField(default=True)
    description = fields.TextField(max_length=300, null=True)

    parent: fields.ForeignKeyNullableRelation['PostCategory'] = fields.ForeignKeyField('models.PostCategory',
                                                                                       on_delete=fields.CASCADE,
                                                                                       null=True,
                                                                                       related_name='children')
    children = fields.ReverseRelation["PostCategory"]
    posts: fields.ReverseRelation["Post"]

    class Meta:
        table = "post_category"

    def __str__(self) -> str:
        return self.name

    class PydanticMeta:
        backward_relations = False
        exclude = ('posts', 'parent')
        allow_cycles = True
        max_recursion = 3

schemas.py

class CreateCategory(PydanticModel):
    name: str
    parent_id: int = None
    discription: str = None


GetCategory = pydantic_model_creator(models.PostCategory, name='GetCategory')


class OutCategory(GetCategory):
    id: int
    name: str

router.py

@category_router.post('/', response_model=schemas.OutCategory)
async def create_category(schema: schemas.CreateCategory, user: models.User = Depends(get_superuser)):
    return await service.category_s.create(schema)


@category_router.get('/', response_model=List[schemas.OutCategory])
async def get_all_category():
    return await service.category_s.filter(parent_id__isnull=True)

swagger output: image

i can't to get parent category and children categories to show,how can i fix?

Mecil9 avatar Sep 20 '22 07:09 Mecil9

Hi,

FastAPI's response_model simply wouldn't accomplish what you want it to do.

I haven't run your code, but my guess is that you need to run:

await Schema.from_tortoise_orm(your_query_here)

You would also need to early-init your models.

https://tortoise-orm.readthedocs.io/en/latest/examples/pydantic.html#relations-early-init

I also don't see the point of the OutCategory schema.

mikkothegeeko avatar Sep 20 '22 21:09 mikkothegeeko

官方说法:pydantic_model_creator需要放在Tortoise.init以后执行,才能生成relation关系。

Event_TooEarly = pydantic_model_creator(Event)
print("Relations are missing if models not initialized:")
print(Event_TooEarly.schema_json(indent=4))


Tortoise.init_models(["__main__"], "models")

Event_Pydantic = pydantic_model_creator(Event)
print("\nRelations are now present:")
print(Event_Pydantic.schema_json(indent=4))

这个问题很大,在fastapi里面,怎么和response_model结合呢?官方不修改机制的话,准备弃坑了

nieoding avatar Oct 19 '22 03:10 nieoding

官方说法:pydantic_model_creator需要放在Tortoise.init以后执行,才能生成relation关系。

Event_TooEarly = pydantic_model_creator(Event)
print("Relations are missing if models not initialized:")
print(Event_TooEarly.schema_json(indent=4))


Tortoise.init_models(["__main__"], "models")

Event_Pydantic = pydantic_model_creator(Event)
print("\nRelations are now present:")
print(Event_Pydantic.schema_json(indent=4))

这个问题很大,在fastapi里面,怎么和response_model结合呢?官方不修改机制的话,准备弃坑了

我已经放弃Tortoise了,回到了sqlmodel的怀抱!

Mecil9 avatar Nov 29 '22 13:11 Mecil9

官方说法:pydantic_model_creator需要放在Tortoise.init以后执行,才能生成relation关系。

Event_TooEarly = pydantic_model_creator(Event)
print("Relations are missing if models not initialized:")
print(Event_TooEarly.schema_json(indent=4))


Tortoise.init_models(["__main__"], "models")

Event_Pydantic = pydantic_model_creator(Event)
print("\nRelations are now present:")
print(Event_Pydantic.schema_json(indent=4))

这个问题很大,在fastapi里面,怎么和response_model结合呢?官方不修改机制的话,准备弃坑了

这也太扯了,一个单文件的应用还好,大一些的应用多几个app目录,那不到处都是初始化? This is ridiculous. It's manageable for a single-file application, but for larger applications with multiple 'app' directories, having to initialize everywhere is just too much.

zhuying412 avatar Feb 07 '24 03:02 zhuying412