-
-
Notifications
You must be signed in to change notification settings - Fork 5.2k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[BUG] SQLAlchemy InvalidRequestError on relationships if one of the model is not yet imported #28
Comments
Thanks for the fix! |
you are more than welcome ! It's great to help on fastapi and its siblings 🐝 🐝 🐝 |
🎉 🍰 |
@dmontagu In my code, I have implemented 2 models named
And, this is the error which I am getting:
|
@Haider8 were you able to solve your issue? I'm getting same error. |
No, I couldn't solve this. I was expecting some kind of reply from the maintainers. |
@Haider8 I might know what is happening, just import "Venue" in your user file, that way the application will be aware of the Venue class...later you can change that import and put it some where else, in a path that the application executes at startup |
I think @sebas-500 is right here; for what it's worth this is more of a sqlalchemy question than a fastapi question (or anything specific to this project generator). Also, @Haider8 the error message you got describes precisely how to address the issue:
|
@Haider8 This is documented in the sqlalchemy docs at the very end of the "Configuring Relationships" section here: https://docs.sqlalchemy.org/en/13/orm/extensions/declarative/relationships.html (just above "Configuring Many-to-Many Relationships"). |
May need the unused import for SQLAlchemy. As the comment says: make sure all SQL Alchemy models are imported before initializing DB otherwise, SQL Alchemy might fail to initialize properly relationships for more details: fastapi/full-stack-fastapi-template#28
https://flake8.readthedocs.io/en/latest/user/error-codes.html The apparently unused imports may be needed for SQLAlchemy. As the code comment says: make sure all SQL Alchemy models are imported before initializing DB otherwise, SQL Alchemy might fail to initialize properly relationships See GitHub issue 28 for more details: fastapi#28
I found this issue on google because I had a similar error. I found a solution for my problem but even if it is not really related to the initial issue, I still want to write my solution here in case someone else had the same problem as me: |
I run into this problem when I was dynamically creating and using material views in Postgres. The first call using them would fail but subsequent ones would work. I'm not sure how exactly to describe how I solved it but I'm going to try just in case someone else comes here. The material view is created using a raw query and then reflected using the standard procedure something like:
So the problem was the fist time the application loaded for some reason
This is so it's not being reflected for the first time in one of my api calls. This solved my problem. |
@sebas-500 thanks for the fix man. Your suggestion fixed the problem I was having with relationships. |
…я багов и не создания таблиц Подробнее: make sure all SQL Alchemy models are imported (app.db.base) before initializing DB otherwise, SQL Alchemy might fail to initialize relationships properly for more details: fastapi/full-stack-fastapi-template#28 Комментарии в функции init_db из проекта fastapi: Tables should be created with Alembic migrations But if you don't want to use migrations, create the tables un-commenting the next line
I'm still having this issue, and this is 100% copy from the SQLAlchemy 2 docs. # parent.py
class Parent(Base):
__tablename__ = "parents"
id: Mapped[int] = mapped_column(primary_key=True)
...
children: Mapped[List["Child"]] = relationship(back_populates="parent")
# child.py
# Also tried from app.models.parent import Parent in this file, no effect.
# Also tried not using Mapped, and just parent = relationship("Parent", back_populates="parent"), also not working
class Child(Base):
__tablename__ = "childs" # 'classname + s' in my case
id: Mapped[int] = mapped_column(primary_key=True)
...
parent: Mapped["Parent"] = relationship(back_populates="parent") |
@dejoma I can suppose that you make like this imports in your code if TYPE_CHECKING:
from child import Child
if TYPE_CHECKING:
from parent import Parent Seems that FORM "reads" schemas in "wrong" (alfabeticaly) order. from child import Child I've tried find description this behavior in the documentation but found nothing. If someone will gave the link it will be very useful. |
I had the same error. I solved it by following
I followed the suggesstion in the error
I added the relationship after class has already been defined. initial code class Location(Base):
__tablename__ = 'locations'
id = Column(Integer,primary_key=True)
city = Column(String(50))
state = Column(String(100))
country = Column(String(50))
zip_code = Column(String(50))
latitude = Column(DECIMAL(20,7))
longitude = Column(DECIMAL(20,7))
address_line1 = Column(Text)
address_line2 = Column(Text)
property = relationship('Property', back_populates='location')
def __repr__(self):
return f'<Location {self.id} >'
this worked for me class Location(Base):
__tablename__ = 'locations'
id = Column(Integer,primary_key=True)
city = Column(String(50))
state = Column(String(100))
country = Column(String(50))
zip_code = Column(String(50))
latitude = Column(DECIMAL(20,7))
longitude = Column(DECIMAL(20,7))
address_line1 = Column(Text)
address_line2 = Column(Text)
def __repr__(self):
return f'<Location {self.id} >'
property = relationship('Property', back_populates='location') |
Describe the bug
The application crashes at start-up, when initializing data if :
To Reproduce
create a new db_models/subitems.py (could be copied from item.py)
It is important that this new model has a relationship to another one, e.g Item
Adapt db_models/item.py with the new
relationship
Declare the new SubItem in db/base.py as per the documentation
Re-build and start the application. The full traceback follows
Expected behavior
The solution should have started normally
Additionnal context
In (most of) real use-cases, the application would have defined some CRUD operation on the new defined model, and consequently imported it here and there.
Thus making it available at the time when creating initial data.
Nevertheless, the error is so annoying and obscure (when it happens) that it deserves a safeguard (see my PR for a suggestion)
The text was updated successfully, but these errors were encountered: