无法使用flask-sqlalchemy创建自动递增的主键 [英] unable to create autoincrementing primary key with flask-sqlalchemy
问题描述
我希望我的模型的主键是一个自动递增的整数.这是我的模型的样子
I want my model's primary key to be an autoincrementing integer. Here is how my model looks like
class Region(db.Model):
__tablename__ = 'regions'
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
name = db.Column(db.String(100))
parent_id = db.Column(db.Integer, db.ForeignKey('regions.id'))
parent = db.relationship('Region', remote_side=id, primaryjoin=('Region.parent_id==Region.id'), backref='sub-regions')
created_at = db.Column(db.DateTime, default=db.func.now())
deleted_at = db.Column(db.DateTime)
上面的代码创建了我的表,但不会使 id
自动递增.因此,如果在我的插入查询中我错过了 id
字段,它会给我这个错误
The above code creates my table but does not make id
autoincrementing. So if in my insert query I miss the id
field it gives me this error
错误:id"列中的空值违反了非空约束
ERROR: null value in column "id" violates not-null constraint
所以我把id
声明改成这样
id = db.Column(db.Integer, db.Sequence('seq_reg_id', start=1, increment=1),
primary_key=True)
还是一样的错误.上面的代码有什么问题?
Still the same error. What is wrong with the code above?
推荐答案
以上代码没有问题.事实上,你甚至不需要 autoincrement=True
或 db.Sequence('seq_reg_id', start=1, increment=1),
因为 SQLAlchemy 会自动设置第一个 Integer
PK 列未标记为 FK 为 autoincrement=True
.
Nothing is wrong with the above code. In fact, you don't even need autoincrement=True
or db.Sequence('seq_reg_id', start=1, increment=1),
as SQLAlchemy will automatically set the first Integer
PK column that's not marked as a FK as autoincrement=True
.
在这里,我已经根据您的设置组合了一个工作设置.SQLAlechemy 的 ORM 将负责生成 id 并用它们填充对象如果您使用基于声明性基的类,您已定义该类来创建对象的实例.
Here, I've put together a working setup based on yours. SQLAlechemy's ORM will take care of generating id's and populating objects with them if you use the Declarative Base based class that you've defined to create instances of your object.
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.debug = True
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://user:password@localhost/testdb'
app.config['SQLALCHEMY_ECHO'] = True
db = SQLAlchemy(app)
class Region(db.Model):
__tablename__ = 'regions'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100))
db.drop_all()
db.create_all()
region = Region(name='Over Yonder Thar')
app.logger.info(region.id) # currently None, before persistence
db.session.add(region)
db.session.commit()
app.logger.info(region.id) # gets assigned an id of 1 after being persisted
region2 = Region(name='Yet Another Up Yar')
db.session.add(region2)
db.session.commit()
app.logger.info(region2.id) # and 2
if __name__ == '__main__':
app.run(port=9001)
这篇关于无法使用flask-sqlalchemy创建自动递增的主键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!