无法使用flask-sqlalchemy创建自动增量主键 [英] unable to create autoincrementing primary key with flask-sqlalchemy

查看:236
本文介绍了无法使用flask-sqlalchemy创建自动增量主键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想我的模型的主键是一个自动增量整数。这里是我的模型如何看起来像/ b>

  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- (db.DateTime,default = db.func.now())
deleted_at = db.Column(db.DateTime)
id
自动增量。所以,如果在我的插入查询中,我错过了 id 字段,它给了我这个错误


错误:列ID中的空值违反了非空约束


所以我改变了 id 声明看起来像这样

  id = db.Column(db.Integer,db.Sequence(' 





同样的错误。上面的代码有什么问题?

解决方案

上面的代码没有问题。事实上,你甚至不需要 autoincrement = True db.Sequence('seq_reg_id',start = 1,increment = 1) / code>,因为SQLAlchemy会自动将未标记为FK的第一个 Integer PK列设置为 autoincrement = True



在这里,我已经根据你的设置了一个工作设置。 SQLAlechemy的ORM将负责生成id和填充对象,如果您使用您定义的基于Declarative Base的类来创建对象实例。

  from flask import Flask 
from flask.ext.sqlalchemy import SQLAlchemy
$ b $ app = Flask(__ name__)
app。调试=真
的app.config [ 'SQLALCHEMY_DATABASE_URI'] = '的PostgreSQL://用户:密码@本地/ TESTDB'
的app.config [ 'SQLALCHEMY_ECHO'] = TRUE
分贝= 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 the Thar')
app.logger.info(region.id)#目前无,持续之前

db.session.add(region)
db.session.commit ()
app.logger.info(region.id)#被赋予一个id后为1
$ b region2 = Region(name ='Yet Another Up Yar')
db.session.add(region2)
db.session.commit()
app .logger.info(region2.id)#和2

if __name__ =='__main__':
app.run(port = 9001)


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)

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

ERROR: null value in column "id" violates not-null constraint

So I changed the id declaration to look like this

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?

解决方案

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.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆