Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
383 views
in Technique[技术] by (71.8m points)

Fastapi sqlalchemy pydantic relational field

I am just a starter in FastAPI/Pydantic & SqlAlchemy - I have two model Post and Category where I want Post should fetch Category name instead of only id

when I try to use the below code it gives following error in console

Any help in solving this is much appreciated thank you!

response -> 1 -> category_name
  field required (type=value_error.missing)

post.py models

class Post(Base):
    __tablename__="post"
    id = Column(Integer, primary_key=True, index=True)
    title=Column(String(50))
    user_id=Column(Integer, ForeignKey("users.id"))
    category_id = Column(Integer, ForeignKey("category.id"))
    category_name=relationship("Category", backref="post")


class Category(Base):
    __tablename__="category"
    id = Column(Integer, primary_key=True, index=True)
    name = Column(String)
     

Pydantic models

class CategoryGet(BaseModel):
    id:int
    name:str

    class Config:
        orm_mode=True



class Post(BaseModel):
     
    id = int
    title=str
    user_id=int
    category_id = int
    category_name=CategoryGet 

    class Config:
        orm_mode=True

My mainapp.py

router = APIRouter()


@router.get("/", response_model=List[schemas.VehicleGet])
def get_vehicle(db: Session = Depends(get_db), skip: int = 0, limit: int = 50) -> Any:
    vehicle = crud.post.get_multi(db, skip=skip, limit=limit)
    return vehicle
question from:https://stackoverflow.com/questions/65650499/fastapi-sqlalchemy-pydantic-relational-field

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I guess the problem is that, you forgot orm_mode=True config for you Post model and consequently it is unable to recognize the category_name field. I hope this will solve but if not you could check this thread where an example and some clarification about relationship handling with pydantic.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...