I am using FlaskSQLAlchemy to connect to a SQLite database. When making an instance of a model, it gives him all the column values except the id which is the primary key.
models.py (only important columns):
class Person(db.Model):
id = db.Column(db.Integer, primary_key=True)
account_id = db.Column(db.Integer, nullable=True)
class Address(db.Model):
id = db.Column(db.Integer, primary_key=True)
order_id = db.relationship("Order", backref="address", lazy=True)
class Order(db.Model):
id = db.Column(db.Integer, primary_key=True)
product_id = db.Column(db.Integer, nullable=False) # za sada jedan item samo
person_id = db.Column(db.Integer, nullable=False)
address_id = db.Column(db.Integer, db.ForeignKey("address.id"), nullable=True)
account_id = db.Column(db.Integer, db.ForeignKey("account.id"), nullable=True)
class Account(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
products = db.relationship("Product", backref="seller", lazy=True)
orders = db.relationship("Order", backref="buyer", lazy=True)
class Product(db.Model):
id = db.Column(db.Integer, primary_key=True)
seller_id = db.Column(db.Integer, db.ForeignKey("account.id"), nullable=False)
When this part of the function gets executed, I get an error.
address = Address(
country=form.country.data) # and some other data
db.session.add(address)
if current_user.is_authenticated:
person = Person( # and some other data
account_id=current_user.id)
db.session.add(person)
print(person.id) #prints None
order = Order(
product_id=product.id,\
address_id=address.id,\
person_id=person.id,\
account_id=current_user.id)
db.session.add(order)
db.session.commit()
The print statement prints id that is None, but prints other attributes(not relationships) just fine. As a result of the person id being None and order.person_id being NOT NULLABLE, I get the following error:
sqlalchemy.exc.IntegrityError: (sqlite3.IntegrityError) NOT NULL constraint failed: order.person_id
[SQL: INSERT INTO "order" (product_id, person_id, date, address_id, account_id) VALUES (?, ?, ?, ?, ?)]
[parameters: (26, None, '2021-02-05 11:01:45.668675', 1, 1)]
(Background on this error at: http://sqlalche.me/e/13/gkpj)
Why is the person id None?