使用 SQLAlchemy,我有一个表示表的类。我有第二个类,它继承自第一个类并覆盖了一些方法。使用哪个类取决于另一个表中的值。我应该如何安排我的代码,以便 SQLAlchemy 在执行查询或访问关系属性时为我创建正确的类?
我的代码看起来像这样:
class Thing(Base):
...
relevant_property = Column(Bool)
class RelatedThing(Base): # Should be used if self.thing.relevant_property is True
...
thing = relationship("Thing")
def do_stuff(self):
return 1
class RelatedThingChild(RelatedThing): # Should be used if self.thing.relevant_property is False
def do_stuff(self):
return 2
class SomethingDifferent(Base):
...
related_thing = relationship("RelatedThing") # Plugging in "RelatedThing" here probably isn't right, but I don't know what is
def get_related_things():
# This function doesn't know which version of RelatedThing it wants. Might even want a mix of both.
return DBSession.query(RelatedThing).all() # Plugging in "RelatedThing" here probably isn't right, but I don't know what is
def use_something_different(sd):
sd.related_thing.do_stuff() # Needs sd.related_thing to be the right class.
更新:这是我相关表的实际数据库架构。代表tests
表的类需要根据series.regression
.
pdiff=# \dS series
Table "public.series"
Column | Type | Modifiers
----------------+-----------------------------+------------------------------------------------------------
series_id | integer | not null default nextval('series_series_id_seq'::regclass)
name | text |
control_domain | text |
test_domain | text |
created | timestamp without time zone | default now()
reload_url | text |
regression | boolean |
Indexes:
"series_pkey" PRIMARY KEY, btree (series_id)
Referenced by:
TABLE "tests" CONSTRAINT "tests_series_id_fkey" FOREIGN KEY (series_id) REFERENCES series(series_id)
TABLE "urls" CONSTRAINT "urls_series_id_fkey" FOREIGN KEY (series_id) REFERENCES series(series_id)
pdiff=# \dS tests
Table "public.tests"
Column | Type | Modifiers
-----------+-----------------------------+---------------------------------------------------------
test_id | integer | not null default nextval('tests_test_id_seq'::regclass)
series_id | integer |
created | timestamp without time zone | default now()
status | text |
Indexes:
"tests_pkey" PRIMARY KEY, btree (test_id)
Check constraints:
"status_check" CHECK (status = ANY (ARRAY['complete'::text, 'running'::text, 'queued'::text, 'failed'::text]))
Foreign-key constraints:
"tests_series_id_fkey" FOREIGN KEY (series_id) REFERENCES series(series_id)
Referenced by:
TABLE "engine_tests" CONSTRAINT "diffs_test_id_fkey" FOREIGN KEY (test_id) REFERENCES tests(test_id)
TABLE "urls_tests" CONSTRAINT "urls_tests_test_id_fkey" FOREIGN KEY (test_id) REFERENCES tests(test_id)