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

2023-11-26

我正在制作一个示例 Fast Api 服务器,使用 Tortoise 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)

表已正确创建。将关键字添加到类别时,数据库状态一切正常。问题是当我想查询类别并包含关键字时。我有这样的代码:

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

在这里调试category_orm我有以下内容:

运行时进行category_orm调试

哪种告诉我它们已加载。 然后当我无法使用 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 field

运行时类别(pydantic)调试

查看tortoise orm的源码了解该函数from_tortoise_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.

但我的关系就是没有归还。有人有类似的经历吗?


当尝试生成 pydantic 模型时会出现此问题beforeTortoise ORM 已初始化。如果你看基本派克例如你会看到所有pydantic_model_creator叫做after Tortoise.init.

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


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

Event_Pydantic = pydantic_model_creator(Event)

或者更方便的方法,使用早期模型初始化借助于Tortoise.init_models()。就像这样:


from tortoise import Tortoise

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

在本例中,主要思想是将 pydantic 和 db 模型拆分为不同的模块,以便导入第一个模块不会导致提前创建第二个模块。并确保通话Tortoise.init_models()在创建 pydantic 模型之前。

可以找到更详细的描述和示例here.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python 的 Tortoise ORM 不返回实体关系(Pyndantic、FastAPI) 的相关文章

随机推荐

  • 使用循环对数据框进行子集化

    我有一个如下所示的数据框 index ID date Amount 2 1001 2010 06 08 0 21 1001 2010 10 08 10 6 1002 2010 08 16 30 5 1002 2010 11 25 20 9
  • pg.rb 分段错误 [Mojave 升级]

    pg rb 中的分段错误 56 版本 导轨 5 2 0 红宝石 2 4 4 PG宝石 0 20 0 升级到 Mac OS mojave 后 我的本地主机服务器遇到了问题 服务器本身启动正常 但是当尝试通过网络浏览器访问它时 它崩溃了 并且出
  • 行动代表。如何获取调用该方法的实例

    我有一个操作 我想知道如何访问调用该方法的实例 Exemple this FindInstance gt this InstanceOfAClass Method this FindInstance gt this InstanceOfAC
  • RS232串口通信 C# win7 .net Framework 3.5 sp1

    你好 我是 C 串口新手 我写了一个c 程序 运行在winXP和win7上 以在机器发送数据时保留从串口接收到的数据 using System IO using System IO Ports using System Threading
  • 嵌入式Python 2.7.2 从用户定义的目录导入模块

    我将 Python 嵌入到具有定义的 API 的 C C 应用程序中 应用程序需要实例化脚本中定义的类 其结构大致如下 class userscript1 def init self do something here def method
  • 将元组列表转换为字典

    我有一个像这样的元组列表 a 1 a 2 a 3 b 1 b 2 c 1 我想通过第一项迭代此键控 因此 例如 我可以打印如下内容 a 1 2 3 b 1 2 c 1 如果不保留一个项目来跟踪第一个项目是否与我围绕元组循环相同 我该如何去做
  • Gmail 未显示正确的字体

    我正在尝试更改电子邮件的字体以打开 sans 但是 我在 Gmail 呈现正确字体时遇到问题 我设法找到解决 Outlook 问题的方法 这就是我所拥有的 body font face font family Open Sans font
  • vim 中的 Zsh 别名如 !gst?

    有没有办法在 vim 中运行我的 zsh 别名 并将输出发送到新的分割 我正在使用 oh my zsh git 别名 例如gst 而我无法做到 gst在 vim 里面 Thanks Try 设置 shell zsh l 并将别名设置为 zs
  • 将 RTSP 存储到文件位置

    我能够通过 C Winform 应用程序在 Windows 7 64 位机器上流式传输 rtsp 这是我使用的库 VLCD点网这是播放 RTSP 流的代码示例 LocationMedia media new LocationMedia rt
  • ActiveMQ 消费者挂起

    我有一个使用 SSL 传输的 activeMQ 代理 我有大约 10 个消费者正在使用该代理 我正在使用骆驼来配置我的路线 每隔一段时间 它就会挂起并且不会消耗新消息 即使我重新启动消费者 即使队列中有待处理的消息 我开始尝试通过一次一个地
  • Visual Studio 2015。文件未添加到 TFS

    我正在使用 Visual Studio 2015 update 3 以及托管在 Visualstudio com 上的 TFS 当我将 C 类文件添加到 Visual Studio 中的一个项目时 它不会自动添加到源代码管理中 对于同一解决
  • 是什么导致我的 java.net.SocketException: 连接重置? [复制]

    这个问题在这里已经有答案了 我们经常看到但间歇性的java net SocketException Connection reset我们的日志中出现错误 我们不确定在哪里Connection reset错误实际上是从哪里来的 以及如何去调试
  • NSdManager ResolveListener 错误代码 3:失败已处于活动状态

    我在 Android 应用程序中使用 NsdManager 来发现由我开发的另一台设备发布的 NSD 服务 我只在Android App上进行服务发现 这一侧不需要服务注册 网络上同时发布了同一类型服务的多个实例 我开始使用Google提供
  • Hibernate Postgresql select for update 与外连接问题

    我在尝试使用 Spring 数据和 Hibernate 作为 JPA 实现和 Postgresql 选择更新行时遇到了问题 假设我们有实体 A B C public class A Id private Long id OneToMany
  • 链式linq查询的顺序执行

    这段代码有什么不同吗 var query DbContext Customers Where
  • 如何从像素中获取颜色? OpenGL

    我想从游戏中的像素获取颜色并将该颜色保存在变量中 在opengl中如何实现呢 glReadPixels include
  • 如何使用adb shell显示本地图像

    我想用adb shell告诉我的设备显示 SD 卡上的图像 我认为这个命令会起作用 adb shell am start a android intent action MAIN n com android browser BrowserA
  • 在 Javascript 函数中获取 MVC 控制器名称

    我有一个Jquery增删改查功能 这是从多个控制器操作中调用的 有什么方法可以找出哪个控制器正在触发该功能 例如 来自视图的函数调用 a Edit Icon live click function event editDialog this
  • db:seed 未加载模型

    我正在尝试用标准为我的数据库播种db seeds rb方法 这在我的开发机器上运行良好 但在我的服务器上 我得到 sudo rake db seed RAILS ENV production trace Invoke db seed fir
  • Python 的 Tortoise ORM 不返回实体关系(Pyndantic、FastAPI)

    我正在制作一个示例 Fast Api 服务器 使用 Tortoise ORM 作为异步 orm 库 但我似乎无法返回我定义的关系 这些是我的关系 Category from tortoise fields data import Datet