带正整数的flask sqlalchemy列约束 [英] flask sqlalchemy column constraint for positive integer
问题描述
如何使用烧瓶sqlalchemy将列定义为正整数?
how can i define a column as a positive integer using flask sqlalchemy?
我希望答案看起来像这样:
i am hoping the answer would look something like this:
class City(db.Model):
id = db.Column(db.Integer, primary_key=True)
population = db.Column(db.Integer, positive=True)
def __init__(self,population):
self.population = population
但是,此类定义将抛出错误b/c sqlalchemy不知道正"参数.
however, this class definition will throw an error b/c sqlalchemy does not know about a 'positive' argument.
i可能会引发异常.但是我不知道如何确保更新后人口仍保持正数.
i could raise an exception if an object is instantiated with a negative value for the population. but i don't know how to ensure that the population remains positive after an update.
感谢您的帮助.
推荐答案
不幸的是,在python方面,sqlalchemy竭尽所能.没有特殊的sqlalchemy"方式来表示instance属性必须满足一些约束:
unfortunately, on the python side, sqlalchemy does its best to stay out of the way; there's no 'special sqlalchemy' way to express that the instance attribute must satisfy some constraint:
>>> class Foo(Base):
... __tablename__ = 'foo'
... id = Column(Integer, primary_key=True)
... bar = Column(Integer)
...
>>> f = Foo()
>>> f.bar = "not a number!"
>>> f.bar
'not a number!'
如果您尝试提交此对象,则sqlalchey 会抱怨,因为它不知道如何将提供的python值呈现为列类型Integer
的SQL.
If you tried to commit this object, sqlalchey would complain because it doesn't know how to render the supplied python value as SQL for the column type Integer
.
如果这不是您想要的,您只想确保不良数据不会到达数据库,则您需要一个Check
约束.
If that's not what you're looking for, you just want to make sure that bad data doesn't reach the database, then you need a Check
Constraint.
class Foo(Base):
__tablename__ = 'foo'
id = Column(Integer, primary_key=True)
bar = Column(Integer)
__table_args__ = (
CheckConstraint(bar >= 0, name='check_bar_positive'),
{})
这篇关于带正整数的flask sqlalchemy列约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!