Reputation: 5780
I have this class:
class Payment(db.Model):
__tablename__ = "payment"
id = db.Column("payment_id", db.Integer, primary_key=True, autoincrement=True)
date = db.Column("payment_date", db.DateTime)
payment_collected = db.Column(db.Integer)
amount_collected = db.Column(db.String(15))
payment_type_id = db.Column("payment_type", db.Integer)
reference_number = db.Column(db.String(255))
is_invoice_data = db.Column(db.Integer)
is_active = db.Column(db.Integer)
payee_user_id = db.Column(db.Integer, db.ForeignKey("user.user_id"))
services_rendered_id = db.Column(
db.Integer, db.ForeignKey("services_rendered.service_id")
)
which maps directly to a table in my database. The column payment_date
(represented by the date
property on the class) is set to default to CURRENT_TIMESTAMP
. However, when calling this class as a constructor like:
new_payment = Payment(
services_rendered_id=new_sr.id,
payment_collected=True,
payment_type_id=payment_type_id,
payee_user_id=payee_id,
amount_collected=amount_collected
)
the generated SQL inserts a value to ALL the map columns, including payment_date
, and passes None for those columns that I do not specify in the constructor.
Example:
INSERT INTO
payment
(payment_date, payment_collected, amount_collected, payment_type, reference_number, is_invoice_data, is_active, payee_user_id, services_rendered_id)
VALUES
(None, 1, '258.40', '7', None, None, None, 3240, 28)
How could I avoid this behavior so that SQLAlchemy does not override the default values I've set in my database?
Upvotes: 0
Views: 87
Reputation: 57600
Setting server_default=db.FetchedValue()
for the date
column will tell SQLAlchemy to get the default value for the column from the database upon INSERT. See the documentation for further information.
Upvotes: 1