如何确定一对一关系?

时间:2017-12-13 18:20:16

标签: python python-2.7 sqlalchemy flask-sqlalchemy

我有第一个Announcements模型:

class Announcements(db.Model):
    __tablename__ = 'announcements'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(150), nullable=False)
    text = db.Column(db.Text(), nullable=False)
    category = db.Column(db.Integer(), nullable=False)
    duplicate = db.Column(db.Integer(), nullable=True)
    advert_id = db.Column(db.Integer(), nullable=True)
    rotate_photo = db.Column(db.Integer(), nullable=True)
    account = db.Column(db.Integer(), nullable=False)

Account模型:

class Accounts(db.Model):
    __tablename__ = 'accounts'
    id = Column(Integer, primary_key=True)
    api_key = db.Column(db.String(150), nullable=False)
    name = db.Column(db.String(150), nullable=True)
    status = db.Column(db.Integer(), nullable=True)

需要通过绑定AnnouncementsAccount设置这些模型之间的一对一关系:Announcements.account = Account.id

我试过了:

class Announcements(db.Model):
    __tablename__ = 'announcements'
    id = db.Column(db.Integer, primary_key=True)
    account = db.Column(db.Integer(), ForeignKey('account.id'), nullable=False)
    parent = db.relationship("Account", back_populates="child")


class Accounts(db.Model):
    __tablename__ = 'accounts'
    id = Column(Integer, primary_key=True)
    api_key = db.Column(db.String(150), nullable=False)
    name = db.Column(db.String(150), nullable=True)
    status = db.Column(db.Integer(), nullable=True)
    child = db.relationship("Announcements", uselist=False, back_populates="parent")

它给了我一个错误:

  

文件   " C:\ Python27 \ lib \ site-packages \ sqlalchemy \ orm \ relationships.py",line   2100,在_determine_joins中       "指定'主要连接' 。表达" %self.prop)sqlalchemy.exc.NoForeignKeysError:无法确定连接条件   在关系Accounts.child上的父/子表之间 - 有   没有连接这些表的外键。确保引用列   与ForeignKey或ForeignKeyConstraint相关联,或指定   ' primaryjoin'表达

0 个答案:

没有答案