I’m having a problem resolving a circular dependency between two tables. Have followed all the information I found, but it still doesn’t quite work.
My tables look like this
run calibration_metric
------------------------------------------- ---------------------------------
run_pk calibration_metric_pk calibration_metric run_pk
1 5 5 1
The relationship from calibration_metric
to run
is many to 1, but from run
to calibration_metric
is 1 to 1
I have the following definitions (extraneous fields removed)
lass Run(ModelBase):
__tablename__ = 'run'
pk = mapped_column(Integer, primary_key=True)
calibration_metric_pk = mapped_column(ForeignKey("calibration_metric.pk", name="fk_run_calibration_metric"))
metric = relationship("CalibrationMetric",
primaryjoin="calibration_metric_pk == CalibrationMetric.pk",
post_update=True)
lass CalibrationMetric(ModelBase):
__tablename__ = 'calibration_metric'
pk = mapped_column(Integer, primary_key=True)
run_pk = mapped_column(ForeignKey("run.pk", name="fk_calibration_metric_run"))
run = relationship("Run")
I have this section, "objective_metric_pk == CalibrationMetric.pk"
, in quotes because without them, Python complained about circular import
I’m getting this error
sqlalchemy.exc.InvalidRequestError: When initializing mapper Mapper[Run(run)], expression 'calibration_metric_pk == CalibrationMetric.pk' failed to locate a name ("name 'calibration_metric_pk' is not defined"). If this is a class name, consider adding this relationship() to the <class 'root.db.models.Run.Run'> class after both dependent classes have been defined.
I can’t figure out why it’s not finding the calibration_metric_pk
Note that I don’t care about getting the list of Calibration_Metric objects in Run, that are associated by the Run primary key. I only care about the 1-1 relationship and getting the Calibration_Metric object pointed to by the calibration_metric_pk field.
But I would also like to have access to the Run object from Calibration_Metric.run_pk. I don’t think I need to specify back_populates
, since I only care about 1 end of each of the relationships