B
B
beduin012018-04-04 17:49:59
SQL
beduin01, 2018-04-04 17:49:59

Why doesn't the ForeignKey constraint work in SQLAlchemy?

The following model is suitable for copy-paste. I can not figure out why the restriction on ForeignKey does not work.

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

engine = create_engine('sqlite:///')
Session = sessionmaker(bind=engine)
sess = Session()
Base = declarative_base()

class Users(Base):
  __tablename__ = 'mans'
  id = Column(Integer, primary_key=True)
  user_id = Column(Integer, ForeignKey("address.id"))
  name = Column(String)
  age = Column(Integer)
  
class Address(Base):
  __tablename__ = 'address'
  id = Column(Integer, primary_key=True)
  email = Column(String)

Base.metadata.create_all(engine)

user1 = Users(id=1, user_id=2, name='Mike', age=21)
adr1 = Address(id=1, email='[email protected]')


sess.add(user1)
sess.add(adr1)

sess.commit()
x = sess.query(Users).filter(Users.id>0).first()

print(x.name)

I put a limit on:
user_id = Column(Integer, ForeignKey("address.id"))

and here I am trying to access a non-existent key:
user1 = Users(id=1, user_id=2, name='Mike', age=21)

user_id=2I don't, but the code works successfully. Why?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question