George
George

Reputation: 72

Python3 auto increment id in constructor database flask

I've a problem with 'id' in constructor. I've a database which describe a new car. Each car has id, model, price. I use a flask to make a web application to add new cars. My database has an autoincrement in field 'id'. How can I create a new instance of the Car Class(id,name,price) if I don't want to type id because it has to know it automatically from database? Please help me with that. Thank you in advance!

Upvotes: 0

Views: 1671

Answers (1)

metmirr
metmirr

Reputation: 4302

You can use flask_sqlalchemy extension. It provides a model which you will inheritance Car class as follows:

from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy(app)

class Car(db.Model):
    __tablename__ = 'cars'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String)
    #other columns ...

id column of Car class will autoincrement, when create an instance don't need to pass id:

car = Car(name="Model A")
db.session.add(car)
db.session.commit()
#check id
car.id

Upvotes: 2

Related Questions