pythonsqlalchemy

sqlalchemy.exc.NoReferencedTableError: Foreign key associated with column could not find table


Im trying to create a relationship between two tables which are in separated classes.

from sqlalchemy import Column, Integer, String, create_engine
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class User(Base):
    __tablename__ = 'user'

    id = Column(Integer, primary_key=True)
    name = Column(String(50))
    age = Column(Integer)

So I want to create a table called order which FK is the user id.

I did this:


from sqlalchemy import (Column, Float, ForeignKey, Integer, String,
                        create_engine)
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship, sessionmaker

engine = create_engine(
    "mysql+pymysql://root:admin@localhost/test", echo=False)

Session = sessionmaker(bind=engine)
session = Session()

Base = declarative_base()


class Order(Base):
    __tablename__ = 'order'

    product = Column(String(50))
    price = Column(Float)
    user_id = Column(
        Integer,
        ForeignKey('user.id', ondelete='CASCADE'), primary_key=True,
        nullable=False,
        # no need to add index=True, all FKs have indexes
    )
    cliente = relationship('User', foreign_keys='Order.user_id')


Base.metadata.create_all(engine)

I get this error:

sqlalchemy.exc.NoReferencedTableError: Foreign key associated with column 'order.user_id' could not find table 'user' with which to generate a foreign key to target column 'id'

Solution

  • you need to add db.relationship in User table not in order table hopefully you get this useful.