当用户的主键更改时,SQLAlchemy更新外键

时间:2018-12-26 07:08:26

标签: python sqlalchemy flask-sqlalchemy

如果我想确保如果用户的主键曾经被更新过或删除过,那么我想确保外键被更新或整个行被删除,那么关系和外键会是什么样子。目前我有这个。

class User(Model):
    __tablename__ = 'users'
    id = db.Column(db.Integer(), primary_key=True)
    username = Column(db.String(80), unique=True, nullable=False)
    name = Column(db.String(100), nullable=False)
    email = Column(db.String(255), unique=True, nullable=False)
    roles = db.relationship('Role', secondary='user_roles')
    announcements = db.relationship('Announcement', backref='author', 
                                    lazy='dynamic')
    user_awk_announcement = db.relationship('ViewedAnnouncement', foreign_keys='ViewedAnnouncement.user_id', backref='user',lazy='dynamic')

    token: str = ''

class ViewedAnnouncement(Model):
    __tablename__ = 'viewed_announcement'
    id = db.Column(db.Integer(), primary_key=True)
    user_id = db.Column(db.Integer(), db.ForeignKey('users.id', onupdate='CASCADE',), onupdate='CASCADE')
    announcement_id = db.Column(db.Integer(), db.ForeignKey('announcement.id',))

基本上现在,如果删除公告或用户,则正确删除了ViewedAnouncement行,但是,如果公告ID或用户ID已更新,则键不会在ViewedAnnouncement表中更新。我应该在数据库中处理此问题而不是使用sqlalchemy吗?

* edit我还添加了nonoucement类(如果有帮助的话)

class Announcement(Model):
    __tablename__ = 'announcement'  # required attribute
    object_name_repr = 'announcement'  # required attribute

    id = Column(db.Integer, primary_key=True)
    title = Column(db.String(100), nullable=False)
    body = Column(db.TEXT, nullable=True)
    created_at = Column(db.DateTime, nullable=False, default=dt.datetime.utcnow)

    user_id = db.Column(db.Integer, db.ForeignKey('users.id'))
    post_awk = db.relationship('ViewedAnnouncement', foreign_keys='ViewedAnnouncement.announcement_id',
                           lazy='dynamic', cascade='all, delete')

0 个答案:

没有答案