2017-07-19 113 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