[Python] Why are the ForeignKey constraints not working? [duplicate]

Discussão em 'Python' iniciado por Stack, Maio 21, 2025.

  1. Stack

    Stack Membro Participativo

    I have this model:

    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='test@mail.ru')


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

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

    print(x.name)


    I can't understand why it's working if I have ForeignKey constrains:

    user_id = Column(Integer, ForeignKey("address.id"))


    And on this line trying to access to nonexistent key:

    user1 = Users(id=1, user_id=2, name='Mike', age=21)

    Continue reading...

Compartilhe esta Página