Python 如何在多对多关系上使用CheckConstraint count?
我有一个基本的Python 如何在多对多关系上使用CheckConstraint count?,python,sqlalchemy,Python,Sqlalchemy,我有一个基本的Person表。每个人最多可以有5个朋友。我希望使用数据库级别的约束强制执行该检查 我已尝试使用此处所述的func.count,但没有成功,出现以下错误: sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) misuse of aggregate function count() 这是我的密码: friend_table = Table( 'friend', Base.metadata, Colu
Person
表。每个人最多可以有5个朋友。我希望使用数据库级别的约束强制执行该检查
我已尝试使用此处所述的func.count
,但没有成功,出现以下错误:
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) misuse of aggregate function count()
这是我的密码:
friend_table = Table(
'friend', Base.metadata,
Column('left_id', Integer, ForeignKey('person.id')),
Column('right_id', Integer, ForeignKey('person.id'))
)
class Person(Base):
__tablename__ = 'person'
id = Column(Integer, primary_key=True)
name = Column(String, nullable=False)
friends = relationship('Person',
secondary=friend_table,
primaryjoin=friend_table.c.left_id == id,
secondaryjoin=friend_table.c.right_id == id)
__table_args__ = (
CheckConstraint(func.count(friends) < 5, name='max_friends_constraint'),
)
friend\u table=table(
'friend',Base.metadata,
列('left_id',Integer,ForeignKey('person.id'),
列('right_id',Integer,ForeignKey('person.id'))
)
班级人员(基本):
__tablename_uuu='person'
id=列(整数,主键=True)
名称=列(字符串,可空=False)
朋友=关系(“人”,
次要=朋友表,
primaryjoin=friend\u table.c.left\u id==id,
secondaryjoin=friend\u table.c.right\u id==id)
__表参数=(
CheckConstraint(函数计数(朋友)<5,name='max\u friends\u constraint'),
)
回答这个老问题,因为我找不到其他令人满意的答案。根据我的调查,这种CheckConstraint
使用连接查询并非不可能,但它仍然非常低效
但是,可以使用事件
,在发生追加
时检查号码,以强制执行最大好友数。下面的代码示例应与您的预期案例相匹配:
from sqlalchemy import event
from sqlalchemy.exc import IntegrityError
@event.listens_for(Person.friends, "append")
def receive_append(target, value, initiator):
if len(target.friends) >= 5:
# Raising this exc just as an example, just adapt to your needs
raise IntegrityError("person.friends.append", None, None)
# This returns the value, hence the friend will be appended normally
return value
如果您只打算使用sqlalchemy,那么这应该是一个很好的解决方案。如果您计划使用原始查询以任何其他形式与数据库交互,那么您可能需要为关联表friend
添加一个trigger
,以强制执行规则