gpt4 book ai didi

python - 如何在 FastAPI 中对模型的所有字段启用过滤

转载 作者:行者123 更新时间:2023-12-04 14:08:16 26 4
gpt4 key购买 nike

在带有 restframework 的 Django 中,你可以这样做:

class Item(models.Model):
id = models.IntegerField()
name = models.CharField(max_length=32)
another_attribute = models.CharField(max_length=32)
...
(more attributes)
...
yet_another_attribute = models.CharField(max_length=32)

class ItemViewSet(viewsets.ReadOnlyModelViewSet):
permission_classes = [IsAuthenticated]
serializer_class = ItemSerializer
filterset_fields = '__all__' # <- this enables filtering on all fields
queryset = Item.objects.all()
如果我想允许过滤, filterset_fields = '__all__'会让我做类似 api/item/?(attribute)=(value) 的事情并允许我过滤任何属性
我正在阅读教程( https://fastapi.tiangolo.com/tutorial/sql-databases/#crud-utils ),看起来涉及很多手动过滤:
from fastapi_sqlalchemy import db

class Item(BaseModel):
id: int
name: str
another_attribute: str
...
(more attributes)
...
yet_another_attribute: str

# is it necessary to manually include all the fields I want to filter on as optional query parameters?
@app.get("/items/")
async def read_item(
db: Session,
id: Optional[int] = None,
name: Optional[str] = None,
another_attribute: Optional[str] = None,
...
(more attributes)
...
yet_another_attribute: Optional[str] = None
):
# and then I'd need to check if the query parameter has been specified, and if so, filter it.
queryset = db.session.query(Item)
if id:
queryset = queryset.filter(Item.id == id)
if name:
queryset = queryset.filter(Item.name == name)
if another_attribute:
queryset = queryset.filter(Item.another_attribute == another_attribute)
...
(repeat above pattern for more attributes)
...
if yet_another_attribute:
queryset = queryset.filter(Item.yet_another_attribute == yet_another_attribute)
实现上述行为的首选方法是什么?是否有任何软件包可以使我免于进行大量手动过滤,从而使我的行为与 Django Rest Framework View 集一样方便?
或者手动包含我想要过滤的所有字段作为可选查询参数,然后检查每个参数,然后过滤是否存在是唯一的方法?

最佳答案

这是可能的,但还不完美:

from fastapi.params import Depends

@app.get("/items/")
async def read_item(item: Item = Depends()):
pass
FastAPI Doku详情。
缺点是可能需要在 Item 类中指定参数。可以使用所有可选参数编​​写子类(例如,如 here 所述)。它适用于类的实例,但 FastAPI 似乎没有反射(reflect) API 文档中的那些。如果有人有解决方案,我很乐意学习。
或者,您可以拥有多个模型,如 here 所述.但我不喜欢这种方法。
要回答您的第二个问题,您可以像这样访问所有通用参数:
@app.get("/items/")
async def read_item(
db: Session,
id: Optional[int] = None,
name: Optional[str] = None,
another_attribute: Optional[str] = None,
...
(more attributes)
...
yet_another_attribute: Optional[str] = None
):
params = locals().copy()
...
for attr in [x for x in params if params[x] is not None]:
query = query.filter(getattr(db_model.Item, attr).like(params[attr]))

关于python - 如何在 FastAPI 中对模型的所有字段启用过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66680866/

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