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?
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.
There can be only one AUTO_INCREMENT column per table, it must be indexed, and it cannot have a DEFAULT value. So you can indeed have an AUTO_INCREMENT column in a table that is not the primary key.
The MS SQL Server uses the IDENTITY keyword to perform an auto-increment feature. In the example above, the starting value for IDENTITY is 1, and it will increment by 1 for each new record. Tip: To specify that the "Personid" column should start at value 10 and increment by 5, change it to IDENTITY(10,5) .
A primary key is by no means required to use the auto_increment property - it just needs to be a unique, not-null, identifier, so the account number would do just fine.
Auto increment is used with the INT data type. The INT data type supports both signed and unsigned values. Unsigned data types can only contain positive numbers. As a best practice, it is recommended to define the unsigned constraint on the auto increment primary key.
You can add an AUTO_INCREMENT
not primary key but you can't have two AUTO_INCREMENT
fields
If you don't have AUTO_INCREMENT
you can add an AUTO_INCREMENT
and UNIQUE
whith something like this:
ALTER TABLE `items` ADD `AutoInc` INT NOT NULL AUTO_INCREMENT, ADD UNIQUE (`AutoInc`)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With