awtkns / fastapi-crudrouter

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

AttributeError: 'FieldInfo' object has no attribute 'name' #190

Closed 0x587 closed 1 year ago

0x587 commented 1 year ago

I got this problem when I just try the demo! Python3.11.4

from pydantic import BaseModel
from fastapi import FastAPI
from fastapi_crudrouter import MemoryCRUDRouter as CRUDRouter

class Potato(BaseModel):
    id: int
    color: str
    mass: float
    pass

app = FastAPI()
app.include_router(CRUDRouter(schema=Potato))

import uvicorn

uvicorn.run(app)

image image

SaladBreaker commented 1 year ago

Hello, I encountered the same problem and by downgrading pydentic to 1.10.6 it got solved. I think this is only a temporary solution and somebody should definitely look into it.

SaladBreaker commented 1 year ago

Duplicate with: https://github.com/awtkns/fastapi-crudrouter/issues/189

0x587 commented 1 year ago

Thanks for your great advice. I found that solving this problem only requires downgrading pydentic to a version below 2.0. Use the command

pip install "pydantic==1.*"

The problem occurs when pydantic2.x modifies

BaseModel.__fields__

I provide a feasible solution here, just modify the schema_factoryfunction on line 22 of core/_utils.py.

# for handle pydantic 2.x migration
from pydantic import __version__ as pydantic_version

if int(pydantic_version.split('.')[0]) >= 2:
    # pydantic 2.x
    fields = {
        fk: (fv.annotation, ...)
        for fk,fv in schema_cls.model_fields.items()
        if fk != pk_field_name
    }
else:
    # pydantic 1.x
    fields = {
        f.name: (f.type_, ...)
        for f in schema_cls.__fields__.values()
        if f.name != pk_field_name
    }

I'll submit a Pull Request to fix this later.