Coder Social home page Coder Social logo

[BUG] SQLAlchemy InvalidRequestError on relationships if one of the model is not yet imported about full-stack-fastapi-postgresql HOT 15 CLOSED

tiangolo avatar tiangolo commented on May 4, 2024
[BUG] SQLAlchemy InvalidRequestError on relationships if one of the model is not yet imported

from full-stack-fastapi-postgresql.

Comments (15)

ebreton avatar ebreton commented on May 4, 2024 8

you are more than welcome ! It's great to help on fastapi and its siblings 🐝 🐝 🐝

from full-stack-fastapi-postgresql.

gruvw avatar gruvw commented on May 4, 2024 7

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 just had the same error message as discussed above, but it wasn't a bug. I just miss-typed the string assigned to the back_populate argument. So just have a look at your back_populate argument referencing the column in your other table, it could be as simple as that 😊

from full-stack-fastapi-postgresql.

Haider8 avatar Haider8 commented on May 4, 2024 6

@dmontagu In my code, I have implemented 2 models named Venue and User like this:

class User(Base):
    id = Column(Integer, primary_key=True, index=True)
    username = Column(String(64), index=True, unique=True)
    email = Column(String(120), index=True, unique=True)
    state = Column(String(30))
    venues = relationship("Venue")
    role = Column(String(10), default="customer")
class Venue(Base):
    id = Column(Integer, primary_key=True, index=True)
    name = Column(String(64), index=True)
    owner_id = Column(Integer, ForeignKey("user.id"))

And, this is the error which I am getting:

sqlalchemy.exc.InvalidRequestError: When initializing mapper mapped class User->user, expression 'Venue' failed to locate a name ("name 'Venue' is not defined"). If this is a class name, consider adding this relationship() to the <class 'app.db_models.user.User'> class after both dependent classes have been defined.

from full-stack-fastapi-postgresql.

dmontagu avatar dmontagu commented on May 4, 2024 4

@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").

from full-stack-fastapi-postgresql.

sebas-500 avatar sebas-500 commented on May 4, 2024 1

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

from full-stack-fastapi-postgresql.

tiangolo avatar tiangolo commented on May 4, 2024

Thanks for the fix!

from full-stack-fastapi-postgresql.

tiangolo avatar tiangolo commented on May 4, 2024

🎉 🍰

from full-stack-fastapi-postgresql.

Haider8 avatar Haider8 commented on May 4, 2024

@ebreton @tiangolo How can I do this exact change here in my repository as I also want to introduce relationships between the db_models

from full-stack-fastapi-postgresql.

dmontagu avatar dmontagu commented on May 4, 2024

@Haider8 If you want to do this "exact change" you can just look at the files changed in #29 . If you want help with something more specific, you need to ask a more specific question.

from full-stack-fastapi-postgresql.

sebas-500 avatar sebas-500 commented on May 4, 2024

@Haider8 were you able to solve your issue? I'm getting same error.

from full-stack-fastapi-postgresql.

Haider8 avatar Haider8 commented on May 4, 2024

No, I couldn't solve this. I was expecting some kind of reply from the maintainers.

from full-stack-fastapi-postgresql.

dmontagu avatar dmontagu commented on May 4, 2024

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:

If this is a class name, consider adding this relationship() to the <class 'app.db_models.user.User'> class after both dependent classes have been defined.

from full-stack-fastapi-postgresql.

princelySid avatar princelySid commented on May 4, 2024

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 error was not the same but similar:
sqlalchemy.exc.InvalidRequestError: Entity namespace for "table_name" has no property "column"

The material view is created using a raw query and then reflected using the standard procedure something like:

from sqlalchemy import Table, MetaData, create_engine
metadata = Metadata()
engine = create_engine(db_uri)
table = Table(table_name, metadata, autoload=True, autoload_with=engine)

So the problem was the fist time the application loaded for some reason table was not reflecting properly. Since this call was made only failed when the fastapi process was restarted, I added the table reflection to before the first call is made:

@app.on_event("startup")
def reflect_mv():
    Table(table_name, metadata, autoload=True, autoload_with=engine)

This is so it's not being reflected for the first time in one of my api calls. This solved my problem.
Hope this is helpful for someone.

from full-stack-fastapi-postgresql.

arghanath007 avatar arghanath007 commented on May 4, 2024

@sebas-500 thanks for the fix man. Your suggestion fixed the problem I was having with relationships.

from full-stack-fastapi-postgresql.

dejoma avatar dejoma commented on May 4, 2024

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")

from full-stack-fastapi-postgresql.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.