awtkns / fastapi-crudrouter

A dynamic FastAPI router that automatically creates CRUD routes for your models
https://fastapi-crudrouter.awtkns.com
MIT License
1.34k stars 156 forks source link

issue with related field from tortoise orm pydantic schema #153

Open minkoonim opened 2 years ago

minkoonim commented 2 years ago

I'm using fastapi + tortoise, problem here is i was keep getting "NoValuesFetched" exception from tortoise when a model has relation with other models.

so I jumped into TortoiseCRUDRouter class and had a look and added a line of code. it should be because from_queryset() and from_tortoise_orm() has fetch_related().

it works fine if given schema is tortoise pydantic basemodel.

def _get_all(self, *args: Any, **kwargs: Any) -> CALLABLE_LIST:
    async def route(pagination: PAGINATION = self.pagination) -> List[Model]:
        skip, limit = pagination.get("skip"), pagination.get("limit")
        query = self.db_model.all().offset(cast(int, skip))

        if limit:
            query = query.limit(limit)
        # query = await self.schema.from_queryset(query) # added
        return query

    return route

and

def _get_one(self, *args: Any, **kwargs: Any) -> CALLABLE:
    async def route(item_id: int) -> Model:
        model = await self.db_model.filter(id=item_id).first()
        # model = await self.schema.from_tortoise_orm(model) # added
        if model:
            return model
        else:
            raise NOT_FOUND

    return route