fastapi Tortoise-ORM、SQLAlchemy、peewee使用orm查询user数据表里面admin用户的例子
时间: 2024-01-25 21:04:08 浏览: 202
好的,以下是使用三个不同 ORM 查询 `user` 表中 `admin` 用户的例子:
### 1. 使用 Tortoise-ORM
```python
from tortoise.queryset import QuerySet
from tortoise.contrib.pydantic import pydantic_model_creator
from tortoise import Tortoise, fields, run_async
class User(models.Model):
id = fields.IntField(pk=True)
username = fields.CharField(max_length=50)
password = fields.CharField(max_length=50)
class Meta:
table = "user"
async def main():
await Tortoise.init(db_url='sqlite://db.sqlite3', modules={'models': ['__main__']})
await Tortoise.generate_schemas()
user_schema = pydantic_model_creator(User, exclude=('id',))
queryset: QuerySet[User] = User.filter(username='admin')
results = await user_schema.from_queryset_single(queryset)
print(results)
await Tortoise.close_connections()
run_async(main())
```
### 2. 使用 SQLAlchemy
```python
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class User(Base):
__tablename__ = 'user'
id = Column(Integer, primary_key=True)
username = Column(String(50))
password = Column(String(50))
def __repr__(self):
return f"<User(username='{self.username}', password='{self.password}')>"
engine = create_engine('sqlite:///db.sqlite3')
Session = sessionmaker(bind=engine)
def main():
session = Session()
user = session.query(User).filter(User.username == 'admin').first()
print(user)
session.close()
if __name__ == '__main__':
main()
```
### 3. 使用 peewee
```python
from peewee import SqliteDatabase, Model, CharField, IntegerField
db = SqliteDatabase('db.sqlite3')
class User(Model):
username = CharField(max_length=50)
password = CharField(max_length=50)
class Meta:
database = db
table_name = 'user'
def main():
db.connect()
db.create_tables([User])
user = User.select().where(User.username == 'admin').first()
print(user)
db.close()
if __name__ == '__main__':
main()
```
注意:以上三个例子都是基于 SQLite 数据库的。如果使用其他数据库,请参考相应 ORM 的文档进行配置。
阅读全文