fastapi(三)查询参数

本文深入探讨了FastAPI框架中如何使用查询参数,包括必填、可选参数的定义方式,以及如何处理多个路径和查询参数。同时,文章还讲解了如何通过Optional类型注解来正确处理可选参数。

当你声明函数参数的时候,如果参数并不是来自路径参数中,那么将被自动视为查询参数。

from fastapi import FastAPI

app = FastAPI()

fake_items_db = [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"}]


@app.get("/items/")
async def read_item(skip: int = 0, limit: int = 10):
    return fake_items_db[skip : skip + limit]

这个查询是一个键值对,在url中的?之后,并且使用&符号隔开。

http://127.0.0.1:8000/items/?skip=0&limit=10
可选参数
当你把查询参数默认值设置为None的时候,这个参数就是可选参数。

async def read_item(item_id: str, q: str = None):

多路径参数和查询参数

@app.get("/users/{user_id}/items/{item_id}")
async def read_user_item(
user_id: int, item_id: str, q: str = None, short: bool = False
):

必须的查询参数
如果查询参数为必须的,可以在声明的时候不添加默认值

@app.get("/items/{item_id}")
async def read_user_item(item_id: str, needy: str):

warnning:
如果在声明参数为可选参数的时候,程序报错,
limit:str=None
Incompatible types in assignment (expression has type “None”, variable has type “int”)
可以使用Optional告诉程序变量的值可以为None
from typing import Optional

async def read_user_item(item_id:str,limit:Optional[int]=None):

<think>好的,我现在需要在FastAPI中实现关联查询,但我不太清楚具体该怎么做。让我先回忆一下之前学过的FastAPI和ORM相关的知识。记得FastAPI推荐使用Pydantic模型来处理数据验证,而数据库操作可能要用到ORM,比如Tortoise ORM或者SQLAlchemy。之前看的引用里提到Tortoise ORM可以和FastAPI集成,处理关系型数据,比如一对多和多对多的关系[^2]。所以可能我需要用Tortoise ORM来建立模型之间的关系,然后通过Pydantic模型返回查询结果。 首先,我应该定义数据模型。比如,假设有两个相关的模型,User和Article,一个用户可以有多篇文章,这是一对多的关系。在Tortoise ORM中,怎么定义这种关系呢?可能是在User模型里定义一个字段,比如articles = fields.ReverseRelation["Article"],而在Article模型里定义user = fields.ForeignKeyField("models.User", related_name="articles")。这样应该就能建立用户和文章之间的一对多关系了。 接下来,在FastAPI的路由处理函数中,如何执行关联查询呢?可能需要使用Tortoise的预取(prefetch)或者fetch_related方法。比如,当获取一个用户时,同时获取他所有的文章。Tortoise的查询可能需要使用annotate或者prefetch_related来加载关联数据。然后,将查询结果转换成Pydantic模型返回给前端。 然后,关于Pydantic模型,可能需要定义包含关联数据的响应模型。比如,UserResponse模型里应该包含一个articles的字段,类型是List[ArticleResponse]。但是,Tortoise的模型转换成Pydantic模型时,可能需要使用from_tortoise_orm或者类似的方法来处理嵌套的关系。记得在Tortoise ORM中,可以配置Pydantic模型来自动生成包含关联字段的结构。 具体的代码步骤可能是这样的:首先定义Tortoise模型,然后初始化Tortoise和FastAPI的集成。之后,创建路由处理函数,使用Tortoise的查询方法获取数据,包括关联的数据。最后,将查询结果序列化为Pydantic模型并返回。 不过,我在实际写代码的时候可能会遇到问题,比如如何处理嵌套查询的性能,或者如何正确地在Pydantic模型中表示关联数据。比如,可能需要使用response_model参数来指定返回的数据结构,确保关联的文章列表也被正确包含进去。另外,数据库迁移工具aerich的使用可能也需要配置,确保模型变更能够应用到数据库中[^2]。 示例代码部分可能需要展示如何定义模型、设置路由、执行查询。比如,在路由函数里,使用User.get().prefetch_related('articles')来获取用户及其所有文章,然后将结果转换成包含articles字段的Pydantic模型。这样前端就能接收到用户信息和关联的文章列表了。 还有,可能需要处理分页或过滤的情况,比如查询某个用户的特定类型的文章。这时候,关联查询可能需要更复杂的条件,比如在prefetch时添加过滤条件,或者在查询时使用annotate来连接其他表。 总结一下,步骤应该是:定义模型关系 → 配置ORM和FastAPI → 编写查询逻辑(使用prefetch或fetch_related) → 序列化为Pydantic模型 → 返回响应。过程中需要注意ORM的查询方法以及Pydantic模型的嵌套结构是否正确。</think>在FastAPI中实现关联查询主要依托于ORM框架(如Tortoise ORM)与Pydantic模型的配合。以下是分步实现方法: ### 一、模型定义 假设实现`用户-文章`的一对多关系: ```python # Tortoise ORM模型 from tortoise import fields, models class User(models.Model): id = fields.IntField(pk=True) username = fields.CharField(50, unique=True) articles = fields.ReverseRelation["Article"] # 反向关系 class Article(models.Model): id = fields.IntField(pk=True) title = fields.CharField(100) content = fields.TextField() author = fields.ForeignKeyField("models.User", related_name="articles") # 外键关联 ``` ### 二、Pydantic响应模型 ```python from pydantic import BaseModel class ArticleResponse(BaseModel): id: int title: str class UserDetailResponse(BaseModel): id: int username: str articles: list[ArticleResponse] # 嵌套关联模型 ``` ### 、关联查询实现 ```python from fastapi import APIRouter from tortoise.contrib.pydantic import pydantic_model_creator router = APIRouter() # 自动生成包含关联数据的Pydantic模型 User_Pydantic = pydantic_model_creator(User, name="User", include=("id", "username")) UserWithArticles = pydantic_model_creator( User, name="UserWithArticles", include=("id", "username", "articles") ) @router.get("/users/{user_id}", response_model=UserDetailResponse) async def get_user_with_articles(user_id: int): user = await User.get(id=user_id).prefetch_related("articles") # 预加载关联数据 return await UserWithArticles.from_tortoise_orm(user) # 转换为嵌套模型 ``` ### 四、执行查询示例 请求`GET /users/1`将返回: ```json { "id": 1, "username": "john", "articles": [ {"id": 1, "title": "FastAPI指南"}, {"id": 2, "title": "ORM实践"} ] } ``` ### 五、复杂关联查询 ```python # 获取用户最近3篇文章 async def get_recent_articles(user_id: int): return await Article.filter(author_id=user_id).order_by("-id").limit(3) ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值