You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Hi! I'm trying to understand if fastapi_crudrouter supports inserting object with nested fields that represent many-to-many relatioships, via the Sqlalchemy ORM.
This is the code I have:
fromsqlalchemyimportcreate_engine, Column, Integer, String, Table, ForeignKeyfromsqlalchemy.ormimportdeclarative_base, relationship, joinedload# Make the engineengine=create_engine("sqlite+pysqlite:///:memory:", future=True, echo=True,
connect_args={"check_same_thread": False})
# Make the DeclarativeMetaBase=declarative_base()
# ------------------------------- SqlAlchemy classes with many to many relationship----------------------------# Declare Classes / Tablesbook_authors=Table('book_authors', Base.metadata,
Column('book_id', ForeignKey('books.id'), primary_key=True),
Column('author_id', ForeignKey('authors.id'), primary_key=True)
)
classBook(Base):
__tablename__='books'id=Column(Integer, primary_key=True)
title=Column(String, nullable=False)
authors=relationship("Author", secondary="book_authors", back_populates='books')
classAuthor(Base):
__tablename__='authors'id=Column(Integer, primary_key=True)
name=Column(String, nullable=False)
books=relationship("Book", secondary="book_authors", back_populates='authors')
# Create the tables in the databaseBase.metadata.create_all(engine)
# ------------------------------- Pydantic classes ----------------------------fromtypingimportListfrompydanticimportBaseModelclassAuthorBase(BaseModel):
id: intname: strclassConfig:
orm_mode=TrueclassBookBase(BaseModel):
id: inttitle: strclassConfig:
orm_mode=TrueclassBookSchema(BookBase):
authors: List[AuthorBase]
classAuthorSchema(AuthorBase):
books: List[BookBase]
fromfastapiimportFastAPI, Depends# ------------------------------- Connect to DB ----------------------------app=FastAPI(title="Bookipedia")
defget_db():
db=Session(bind=engine)
try:
yielddbfinally:
db.close()
# ------------------------------- Routers ----------------------------fromfastapi_crudrouterimportSQLAlchemyCRUDRouterrouters= [SQLAlchemyCRUDRouter(schema=AuthorSchema, create_schema=AuthorSchema, db_model=Author, db=get_db),
SQLAlchemyCRUDRouter(schema=BookSchema, create_schema=BookSchema, db_model=Book, db=get_db)]
app.include_router(routers[0])
app.include_router(routers[1])
importuvicornif__name__=="__main__":
uvicorn.run('app:app', port=8080, reload=True, debug=True)
# Go to: http://127.0.0.1:8000/docs
But if one goes to http://127.0.0.1:8000/docs and then to POST/ Books, in the "Try it out" feature, and adds this set of data:
File "C:\Python310\lib\site-packages\sqlalchemy\orm\attributes.py", line 1765, in emit_backref_from_collection_append_event
child_state, child_dict = instance_state(child), instance_dict(child)
AttributeError: 'dict' object has no attribute '_sa_instance_state'
I wanted to understand if I'm doing something wrong, or this use case is not supported by fastapi_crudrouter.
Thanks!
The text was updated successfully, but these errors were encountered:
Adding another example with SQLModel (which subclasses Pydantic's BaseModel and SQLAlchemy's DeclarativeMeta avoiding the need to declare model and schema separately).
The above example would look something like this. The tables are set up properly, but the API doesn't show neither authors nor books fields.
Hi! I'm trying to understand if fastapi_crudrouter supports inserting object with nested fields that represent many-to-many relatioships, via the Sqlalchemy ORM.
This is the code I have:
But if one goes to
http://127.0.0.1:8000/docs
and then toPOST/ Books
, in the "Try it out" feature, and adds this set of data:It doesn't work, it returns this error:
I wanted to understand if I'm doing something wrong, or this use case is not supported by fastapi_crudrouter.
Thanks!
The text was updated successfully, but these errors were encountered: