0

私は以下のマップされたクラスを持っています。これは他の2つのクラスからの関連です。他の多対多のSqlAlchemy関係多対多

class InstanceCustomer(Base): 
__tablename__ = 'Instances_Customers_Association' 

cust_id = Column(Integer, ForeignKey('Customers.id'), primary_key=True) 
inst_id = Column(Integer, ForeignKey('Instances.id'), primary_key=True) 

customer = relationship(Customer, backref=backref('customer')) 
instance = relationship(Instance, backref=backref('instance')) 

def __init__(self, cust_id=None, inst_id=None): 
    self.cust_id = cust_id 
    self.inst_id = inst_id 

def __repr__(self): 
    return "<InstanceCustomer(cust_id='%s', inst_id='%s')>" % (self.cust_id, self.inst_id) 

私はこれをPersonクラスに関連付けたいと考えています。 1人のInstanceCustomerが多くのPersonを持つことができ、1人が多くのインスタンスCustomerを持つことができるように、私はそれらの間に別の関係が必要です。プライマリ・キー/フォーリン・キーにも問題はありますか?

はここでクラスPerson

class Person(Base): 
     __tablename__ = 'person' 
     id = Column(Integer, primary_key=True) 

答えて

0

はNです:Nの関係は、相互関係テーブルを必要としています。例:

Class A(Base): 
    id = Column(Integer, primary_key=True) 

Class B(Base): 
    id = Column(Integer, primary_key=True) 
    As = relationship(
     'A', 
     secondary=AnB, 
     backref=backref('Bs') 
    ) 

AnB = Table(
    "table_a_to_b", 
    Base.metadata, 
    Column(
     'a_id', 
     Integer, 
     ForeignKey('A.id') 
    ), 
    Column(
     'b_id', 
     Integer, 
     ForeignKey('B.id') 
    ) 
) 

Sqlalchemy doc

+0

ありがとうございました!私はInstanceCustomerが既に2つの主キーを持っているので、苦労しているだけです。それに対処できません –

+0

これらの2つの外部キーを主キーとして使う必要はありません。主キーとして自動増分int idを使用します。必要に応じて、固有のキーを使用して1つのペア(a_id、b_id)が存在することを確認します。 – Valens

+0

もし私がundderstand(a_id、b_id)を合成キーにすべきではないが、他のプライマリキーが自動的にインクリメントされているかどうかを確認する必要があります。 しかし、私の問題は、InstanceCustomerが、構成された主キーで構成されていることです。これは相互関係テーブルにある必要があります。しかし、私はそれらをインポートしようとすると、SQLAlchemyは文句を言う: "テーブルをリンクする複数の外部キーのパスなど..."しかし、私は関係にforeign_key引数を提供しても、メッセージが持続する –