如何在SQLAlchemy中设置两个表之间的关系?

时间:2017-12-02 16:35:24

标签: python sqlalchemy flask-sqlalchemy

我有两张桌子:

  1. 公告
  2. AnnouncementsSchedule
  3. 按键的关系为one(Announcements)many(AnnouncementsSchedule)

    Announcements.id = AnnouncementsSchedule.announcements_id
    

    我试图在SQLAlchemy中描述模型:

    第一个表被描述为模型:

    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)
        subcategory = db.Column(db.Integer(), nullable=False)
        offer_type = db.Column(db.Integer(), nullable=False)
        url = db.Column(db.String(150), nullable=True)
        status = db.Column(db.Integer(), nullable=False)
        #children = relationship("AnnouncementsSchedule", back_populates="announcements")
    

    第二是:

    class AnnouncementsSchedule(db.Model):
        __tablename__ = 'announcements_schedule'
        id = Column(Integer, primary_key=True)
        week_day = db.Column(db.Integer(), nullable=True)
        week_all = db.Column(db.Integer(), nullable=False)
        time = db.Column(db.Time(), nullable=False)
        announcement_id = Column(Integer, ForeignKey('announcements.announcements_id'))
    

    我做错了什么?

1 个答案:

答案 0 :(得分:0)

列名中有错误(公告没有 announcement_id ):

# announcement_id = Column(Integer, ForeignKey('announcements.announcements_id'))
# change to ->
announcement_id = Column(Integer, ForeignKey('announcements.id'))