Skip to content
Advertisement

How can I set model defaults based on a SqlAlchemy relationship?

Let’s say I have the following models:

JavaScript

I would like to be able to default the Shipment.ship_date to be the day before the Treatment.treatment_date. In other words, I want to do the following:

JavaScript

How do I set defaults based on relationships when they’re set dynamically by methods like append?


For clarification, this is a question about SqlAlchemy and when relationships are set up. For example, I’ve tried the following:

JavaScript

But that throws a TypeError because SqlAlchemy hasn’t set up the self.customer field yet.

Advertisement

Answer

It appears as though SQLAlchemy does not configure relationships both ways until after the model has been added and committed to the session.

JavaScript

While this is annoying and I’m not sure why SQLAlchemy doesn’t populate the two-way relationship when one side is created, it can be resolved by manually setting the relationship on both sides. For example:

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement