B
B
beduin012018-03-01 18:45:33
Python
beduin01, 2018-03-01 18:45:33

Why is the relationship between tables not established through ForeignKey?

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

engine = create_engine('sqlite:///:memory:', echo=True)
Session = sessionmaker(bind=engine)
sess = Session()
Base = declarative_base()

class User(Base):
  __tablename__ = 'users'

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

class Address(Base):
  __tablename__ = 'addresses'
  id = Column(Integer, primary_key=True)
  email = Column(String, nullable=False)
  user_id = relationship('User', ForeignKey('Users.id'))

Base.metadata.create_all(engine)

Error:
AttributeError: 'ForeignKey' object has no attribute 'foreign_keys'

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
Leonid, 2018-03-01
@beduin01

something like this:

class Address(Base):
  __tablename__ = 'addresses'
  id = Column(Integer, primary_key=True)
  email = Column(String, nullable=False)
  user_id = Column(Integer, ForeignKey('users.id'))
  user = relationship(User)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question