Unique one-to-many column constraint in SQLAlchemy & MySQL

I am not sure I correctly named this question. I can add a unique constraint, good enough for any of my tables, but in the example below, I'm not sure how to do what I need:

class Branch(db.Model):
    id = db.Column(db.Integer, primary_key = True)
    name = db.Column(db.String(160))
    #foreign key for 'branches' in Account class. access with Branch.account
    account_id = db.Column(db.Integer, db.ForeignKey('account.id'))

class Account(db.Model):
    id = db.Column(db.Integer, primary_key = True)
    name = db.Column(db.String(160), unique=True)
    branches = db.relationship('Branch', backref = 'account', lazy = 'dynamic')

Therefore, when I added a unique constraint to the column column of the Branch table name, I could not add branches with the same name to different accounts. For example, Seattle may be an affiliate for AccountA and AccountB.

What I want to do is apply a constraint that checks for uniqueness only if account.id is the same. Is it possible?

+4
1

dirn, , :

__table_args__ = (db.UniqueConstraint('account_id', 'name', name='_account_branch_uc'),
                 )

Branch, alembic :

def upgrade():
    op.create_unique_constraint('_account_branch_uc', 'branch', ['name','account_id'])

, , , alebmic, , . , , .

, __table_args__ !

+4

Source: https://habr.com/ru/post/1569566/


All Articles