How is a unique constraint across three columns defined?

坚强是说给别人听的谎言 提交于 2020-08-20 06:17:04

问题


The following EventInvitation model is a simple invitation for one event, sent from a user to another user. I would like to ensure that the invitations are unique across three columns: to_user, from_user and event.

class EventInvitation(db.Model):
    __tablename__ = 'event_invitations'

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

    event_id = db.Column(db.Integer, db.ForeignKey('events.id'))
    event = db.relationship('Event',  foreign_keys=[event_id])
    created = db.Column(db.DateTime(), default=datetime.now)
    updated = db.Column(db.DateTime(), default=datetime.now,onupdate=datetime.now)

    from_id = db.Column(db.Integer, db.ForeignKey('users.id'))
    from_user = db.relationship('User',  foreign_keys=[from_id])

    to_id = db.Column(db.Integer, db.ForeignKey('users.id'))
    to_user = db.relationship('User',  foreign_keys=[to_id])

    cstrt = db.UniqueConstraint('event_id', 'from_id','to_id', name='uix_1')

I tried with this cstrt column but it doesn't work. The constraint should work on SQLite, as well as on MySQL in production. How can I define this unique constraint?


回答1:


You need to add the constraint to the table, not the model. To do this using declarative:

class EventInvitation(db.Model):
    # ...
    __table_args__ = (
        db.UniqueConstraint(event_id, from_id, to_id),
    )

If the table has already been created in the database, you'll need to drop the table and run db.create_all() again, or use Alembic to alter the existing table with a migration.



来源:https://stackoverflow.com/questions/26895207/how-is-a-unique-constraint-across-three-columns-defined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!