Mysql
 sql >> Base de Dados >  >> RDS >> Mysql

No SQLAlchemy, como crio um relacionamento ForeignKey em 2 arquivos .py diferentes?


A chave é usar a mesma Base para ambas as chaves estrangeiras, em vez de criar uma nova para cada tabela.

basetest.py
from sqlalchemy import create_engine, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship, backref
from sqlalchemy import Column, Integer, String
from sqlalchemy import Table, Text

engine = create_engine('mysql://test:[email protected]/test1',
                    echo=False)

Base = declarative_base()

user_models.py
from sqlalchemy import Column, Integer, String
from sqlalchemy import Table, Text


#Base = declarative_base()
from basetest import Base

class Users(Base):
    __tablename__ = 'account_users'
    __table_args__ = {'extend_existing':True}
    id = Column(Integer, primary_key = True)
    username = Column(String(255), nullable=False)    

Base.metadata.create_all(engine)

groups_models.py
from sqlalchemy import create_engine, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship, backref
from sqlalchemy import Column, Integer, String
from sqlalchemy import Table, Text

from basetest import Base
#Base = declarative_base()
from test1 import Users

class Groups(Base):
    __tablename__ = 'personas_groups'
    __table_args__ = {'extend_existing':True}
    id = Column(Integer, primary_key = True )
    user_id = Column(Integer, ForeignKey('account_users2.id')) #This creates an error!!!
    user = relationship(Users) #this probably won't work. But haven't hit this line yet.

Base.metadata.create_all(engine)

Certifique-se de ter a mesma Base para criar todas as tabelas relacionadas.