I am using Flask extension for SQLAlchemy to define my database model. I want an id column to be int type and with auto_increment property but without making it a primary key. How do I achieve it?
我正在使用Flask扩展来为SQLAlchemy定义我的数据库模型。我想要一个id列是int类型和auto_increment属性,但没有使它成为主键。我该如何实现?
I tried this:
我试过这个:
from flask import Flask, jsonify
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:ajay@localhost/pydb'
app.config['SQLALCHEMY_ECHO'] = True
db = SQLAlchemy(app)
class Scenario(db.Model):
scid = db.Column(db.Integer, nullable=False, unique=True, autoincrement=True)
scenario_name = db.Column(db.String(100), primary_key=True)
scenario_description = db.Column(db.String(200), nullable=False)
image_id = db.Column(db.Integer, db.ForeignKey('images.id', onupdate='CASCADE', ondelete='CASCADE'))
def __init__(self, scenario_name, scenario_description, image_id=None):
self.scenario_name = scenario_name
self.scenario_description = scenario_description
self.image_id = image_id
def __repr__(self):
return '<Scenario %r, %r, %r>' % (self.scenario_name, self.scenario_description, self.image_id)
but this doesn't set the scid column as auto_increment.
但是这不会将scid列设置为auto_increment。
1 个解决方案
#1
1
You can add an AUTO_INCREMENT
not primary key but you can't have two AUTO_INCREMENT
fields
您可以添加AUTO_INCREMENT而不是主键,但不能有两个AUTO_INCREMENT字段
If you don't have AUTO_INCREMENT
you can add an AUTO_INCREMENT
and UNIQUE
whith something like this:
如果你没有AUTO_INCREMENT,你可以添加一个AUTO_INCREMENT和UNIQUE,如下所示:
ALTER TABLE `items` ADD `AutoInc` INT NOT NULL AUTO_INCREMENT, ADD UNIQUE (`AutoInc`)
#1
1
You can add an AUTO_INCREMENT
not primary key but you can't have two AUTO_INCREMENT
fields
您可以添加AUTO_INCREMENT而不是主键,但不能有两个AUTO_INCREMENT字段
If you don't have AUTO_INCREMENT
you can add an AUTO_INCREMENT
and UNIQUE
whith something like this:
如果你没有AUTO_INCREMENT,你可以添加一个AUTO_INCREMENT和UNIQUE,如下所示:
ALTER TABLE `items` ADD `AutoInc` INT NOT NULL AUTO_INCREMENT, ADD UNIQUE (`AutoInc`)