Python的乌龟ORM不返回实体关系(Pyndantic、FastAPI)

2024-04-27 03:45:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我制作了一个示例Fast Api服务器,其中使用了Ortoise ORM作为异步ORM库,但我似乎无法返回我定义的关系。这是我的亲戚:

# Category
from tortoise.fields.data import DatetimeField
from tortoise.models import Model
from tortoise.fields import UUIDField, CharField
from tortoise.fields.relational import ManyToManyField
from tortoise.contrib.pydantic import pydantic_model_creator


class Category(Model):
    id = UUIDField(pk=True)
    name = CharField(max_length=255)
    description = CharField(max_length=255)
    keywords = ManyToManyField(
        "models.Keyword", related_name="categories", through="category_keywords"
    )
    created_on = DatetimeField(auto_now_add=True)
    updated_on = DatetimeField(auto_now=True)



Category_dto = pydantic_model_creator(Category, name="Category", allow_cycles = True)
# Keyword
from models.expense import Expense
from models.category import Category
from tortoise.fields.data import DatetimeField
from tortoise.fields.relational import ManyToManyRelation
from tortoise.models import Model
from tortoise.fields import UUIDField, CharField
from tortoise.contrib.pydantic import pydantic_model_creator


class Keyword(Model):
    id = UUIDField(pk=True)
    name = CharField(max_length=255)
    description = CharField(max_length=255)
    categories: ManyToManyRelation[Category]
    expenses: ManyToManyRelation[Expense]
    created_on = DatetimeField(auto_now_add=True)
    updated_on = DatetimeField(auto_now=True)

    class Meta:
        table="keyword"


Keyword_dto = pydantic_model_creator(Keyword)

表已正确创建。向类别添加关键字时,db状态良好。问题是当我想查询类别并包含关键字时。我有以下代码:

class CategoryRepository():

    @staticmethod
    async def get_one(id: str) -> Category:
        category_orm = await Category.get_or_none(id=id).prefetch_related('keywords')
        if (category_orm is None):
            raise NotFoundHTTP('Category')
        return category_orm

在这里调试类别\u orm我有以下几点:

category_orm debug at run-time

这告诉我他们已经上膛了。 当我不能使用Pydantic模型时,我就有了这个代码

class CategoryUseCases():

    @staticmethod
    async def get_one(id: str) -> Category_dto:
        category_orm = await CategoryRepository.get_one(id)
        category = await Category_dto.from_tortoise_orm(category_orm)
        return category

在调试时,没有keywords字段

category (pydantic) debug at run-time

查看函数from_tortoise_orm的乌龟orm源代码

@classmethod
    async def from_tortoise_orm(cls, obj: "Model") -> "PydanticModel":
        """
        Returns a serializable pydantic model instance built from the provided model instance.

        .. note::

            This will prefetch all the relations automatically. It is probably what you want.

但我的亲戚就是不回来。有人有类似的经历吗


Tags: fromimportidtruefieldsmodelmodelsorm
1条回答
网友
1楼 · 发布于 2024-04-27 03:45:28

当在初始化龟ORM之前尝试生成pydantic模型时,就会出现此问题。如果您查看basic pydantic示例,您将看到所有pydantic_model_creator都在Tortoise.init之后调用

显而易见的解决方案是在乌龟初始化后创建pydantic模型,如下所示:


await Tortoise.init(db_url="sqlite://:memory:", modules={"models": ["__main__"]})
await Tortoise.generate_schemas()

Event_Pydantic = pydantic_model_creator(Event)

或者更方便的方法是,通过Tortoise.init_models()使用早期模型init。像这样:


from tortoise import Tortoise

Tortoise.init_models(["__main__"], "models")
Tournament_Pydantic = pydantic_model_creator(Tournament)

在这种情况下,主要思想是将pydantic和db模型拆分为不同的模块,以便导入第一个模块不会导致提前创建第二个模块。并确保在创建pydantic模型之前调用Tortoise.init_models()

更详细的示例说明见here

相关问题 更多 >