gpt4 book ai didi

python - 如何使用 tortoise ORM 执行 native SQL

转载 作者:行者123 更新时间:2023-12-03 08:15:56 30 4
gpt4 key购买 nike

我想使用tortoise ORM来执行原生SQL。我应该怎么办?我找不到执行此操作的方法或类。

最佳答案

有多种execute_*methods您可以随意执行原始 SQL 代码。下面是来自官方documentation的基本示例:

"""
This example demonstrates executing manual SQL queries
"""
from tortoise import Tortoise, fields, run_async
from tortoise.models import Model
from tortoise.transactions import in_transaction


class Event(Model):
id = fields.IntField(pk=True)
name = fields.TextField()
timestamp = fields.DatetimeField(auto_now_add=True)


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

# Need to get a connection. Unless explicitly specified, the name should be 'default'
conn = Tortoise.get_connection("default")

# Now we can execute queries in the normal autocommit mode
await conn.execute_query("INSERT INTO event (name) VALUES ('Foo')")

# You can also you parameters, but you need to use the right param strings for each dialect
await conn.execute_query("INSERT INTO event (name) VALUES (?)", ["Bar"])

# To do a transaction you'd need to use the in_transaction context manager
async with in_transaction("default") as tconn:
await tconn.execute_query("INSERT INTO event (name) VALUES ('Moo')")
# Unless an exception happens it should commit automatically

# This transaction is rolled back
async with in_transaction("default") as tconn:
await tconn.execute_query("INSERT INTO event (name) VALUES ('Sheep')")
# Rollback to fail transaction
await tconn.rollback()

# Consider using execute_query_dict to get return values as a dict
val = await conn.execute_query_dict("SELECT * FROM event")
print(val)
# Note that the result doesn't contain the rolled-back "Sheep" entry.


if __name__ == "__main__":
run_async(run())

关于python - 如何使用 tortoise ORM 执行 native SQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69401708/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com