2013-03-07 100 views
3

我遇到很多麻煩,弄清楚如何正確構建我定義的表的ForeignKey列。我在這裏列出我的模型(並把註釋旁有問題的線在我的******中國型號):如何構建具有複合主鍵的表的外鍵?

class AreaCode(db.Model): 
    __tablename__ = 'areacodes' 
    area_code = db.Column(db.Integer, primary_key=True) 
    exchanges = db.relationship('Exchanges', backref='area_code') 


class Exchange(db.Model): 
    __tablename__ = 'exchanges' 
    exchange = db.Column(db.Integer, primary_key=True) 
    area_code_pk = db.Column(db.Integer, db.ForeignKey('areacodes.area_code'), primary_key=True) 


class PhoneNumber(db.Model): 
    __tablename__ = 'phonenumbers' 
    phone_number = db.Column(db.Numeric(precision=4, scale=0), primary_key=True) 
    exchange_pk = db.Column(db.Integer, db.ForeignKey('exchanges.exchange'), primary_key=True) # this doesnt work since Exchange has two primary keys 

這裏發生的事情:

我兌換表有一個複合主鍵。這是我的用例所必需的。

我想要定義PhoneNumber表需要一個ForeignKey到Exchange表,但由於Exchange表有一個複合主鍵,我無法弄清楚如何使關係工作。

任何指導,將不勝感激。謝謝。

+0

在您的示例中,Exchange只有一個主鍵? 「exchange」欄也應該是「primary = True」嗎? – shazow 2013-03-07 00:46:12

+0

值得一看的東西:http://docs.sqlalchemy.org/en/latest/core/schema.html#sqlalchemy.schema.PrimaryKeyConstraint http://stackoverflow.com/questions/10525797/sqlalchemy-relation- table-with-composite-primary-key 另外,你使用的是哪個數據庫? – shazow 2013-03-07 01:03:08

+0

嗨@shazow,你是對的,我在那裏輸錯了。 Exchange有兩個主鍵。另外,我正在使用PostgreSQL 9.2。 – rdegges 2013-03-07 01:22:34

回答

1

因此,在與sqlalchemy郵件列表上的幾位優秀人士交談之後,我終於找到了上述問題。以下是我的代碼的最終版本,它允許我在表格之間正確關聯:

class AreaCode(db.Model): 
    __tablename__ = 'areacodes' 

    area_code = db.Column(db.Integer, primary_key=True) 


class Exchange(db.Model): 
    __tablename__ = 'exchanges' 

    exchange = db.Column(db.Integer, primary_key=True) 
    area_code_pk = db.Column(db.Integer, db.ForeignKey('areacodes.area_code'), 
          primary_key=True) 
    area_code = db.relationship('AreaCode', backref=db.backref('exchanges', lazy='dynamic')) 


class PhoneNumber(db.Model): 
    __tablename__ = 'phonenumbers' 
    __table_args__ = (
     db.ForeignKeyConstraint(
      ['exchange_exchange', 'exchange_area_code_pk'], 
      ['exchanges.exchange', 'exchanges.area_code_pk'], 
     ), 
    ) 

    phone_number = db.Column(db.Integer, primary_key=True) 
    exchange_exchange = db.Column(db.Integer, primary_key=True) 
    exchange_area_code_pk = db.Column(db.Integer, primary_key=True) 
    exchange = db.relationship('Exchange', backref=db.backref('phone_numbers', lazy='dynamic'))