2017-07-19 146 views
0

嘗試出站電子郵件(子級),源(父級1)和目標(父級2)之間的一對多關係。我正在嘗試使用flask-migrate來設置數據庫。我使用的命令:一對多關係| Flask-SQLAlchemy和Flask-Migrate

python manage.py db migrate 

得到以下錯誤:

sqlalchemy.exc.NoReferencedTableError: Foreign key associated with column 'outbound_emails.target_id' could not find table 'targets' with which to generate a foreign key to target column 'id' 

這是我到目前爲止有:

class Contact(Base): 
    __abstract__ = True 
    id = db.Column(db.Integer, primary_key=True) 
    first_name = db.Column(db.Text, nullable=False) 
    last_name = db.Column(db.Text, nullable=False) 
    email = db.Column(db.Text, nullable=False) 
    phone = db.Column(db.Text, nullable=False) 
    created_at = db.Column(db.DateTime, default=datetime.utcnow()) 
    last_activity = db.Column(db.DateTime, default=datetime.utcnow()) 
    json_data = db.Column(sqlalchemy.dialects.postgresql.JSON) 

    def __init__(self, first_name, last_name, email, phone, 
       created_date=datetime.utcnow(), last_activity=datetime.utcnow(), json_data=None): 
     if json_data is None: 
      json_data = {} 
     self.first_name = first_name 
     self.last_name = last_name 
     self.email = email 
     self.phone = phone 
     self.created_date = created_date 
     self.last_activity = last_activity 
     self.json_data = json_data 


class Target(Contact): 
    __tablename__ = 'targets' 
    outbound_emails = db.relationship("OutboundEmail", backref="target", lazy='dynamic') 

    @property 
    def __repr__(self): 
     return '<target_id {}>'.format(self.target_id) 


class Source(Contact): 
    __tablename__ = 'sources' 
    outbound_emails = db.relationship("OutboundEmail", backref="source", lazy='dynamic') 

    @property 
    def __repr__(self): 
     return '<source_id {}>'.format(self.source_id) 


class OutboundEmail(db.Model): 
    __tablename__ = 'outbound_emails' 
    email_id = db.Column(db.Integer, primary_key=True) 
    provider_id = db.Column(db.Text, nullable=True) 
    source_id = db.Column(db.Integer, db.ForeignKey("sources.id")) 
    target_id = db.Column(db.Integer, db.ForeignKey("targets.id")) 
    data = db.Column(sqlalchemy.dialects.postgresql.JSON) 

    def __init__(self, provider_id, source, target, merge_fields): 
     self.provider_id = provider_id 
     self.source = source 
     self.target = target 
     self.data = merge_fields 


    @property 
    def __repr__(self): 
     return '<email_id {}>'.format(self.email_id) 

有誰看到我在做什麼錯在這裏?謝謝!

回答

0

該解決方案可能取決於您試圖實現哪種類型的繼承,無論是單表,具體表還是連接表繼承。

考慮到您已標記的基類_abstract_我想你想每個子類映射到其獨特的表,因此利用混凝土繼承的一種形式。

在這種情況下,您需要明確定義每個子類上的所有列,即使是那些具有相同名稱的列。所以至少你需要設置:

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

你的派生類。

除此之外,您可能還需要在您的子類中設置多態身份,並可能將其擴展爲允許多態加載。我建議看看關於這個話題的wonderful SQLAlchemy documentation