Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

python - How is a unique constraint across three columns defined?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...