【问题标题】:Python SQLAlchemy/Elixer QuestionPython SQLAlchemy/Elixer 问题
【发布时间】:2010-12-03 22:49:26
【问题描述】:

我正在尝试定义一个可以描述以下关系的 SQLAlchemy/Elixer 模型。我有一个 SSP 表,它有多个 POC 表的外键。我已经在 SSP 对象中正确定义了 ManyToOne 关系(允许我正确地SSP.get(1).action.first_name)。我还想补充的是这种关系的另一面,我可以在其中执行POC.get(1).csa 之类的操作并返回一个 SSP 对象列表,其中将此 POC 定义为 idPOCCSA。

我知道这对于多态关联来说是最好的,但我真的根本无法更改数据库架构(创建一个新的 poc2ssp 表,其中包含一个关联 type 的列)。

class POC(Entity):
  using_options(tablename = 'poc', autoload = True)

  # These two line visually display my "issue":
  # csa = OneToMany('SSP')
  # action = OneToMany('SSP')


class SSP(Entity):
  '''
  Many to One Relationships:
  - csa: ssp.idPOCCSA = poc.id
  - action: ssp.idPOCAction = poc.id
  - super: ssp.idSuper = poc.id
  '''
  using_options(tablename = 'spp', autoload = True)

  csa = ManyToOne('POC', colname = 'idPOCCSA')
  action = ManyToOne('POC', colname = 'idPOCAction')
  super = ManyToOne('POC', colname = 'idPOCSuper')

有什么想法可以做到这一点吗? Elixer FAQ 有一个利用 primaryjoin 和 foreign_keys 参数的好例子,但我在文档中找不到它们。我有点希望 OneToMany() 只支持像 ManyToOne() 那样的 colname 参数。一些不那么冗长的东西。

【问题讨论】:

    标签: python orm sqlalchemy python-elixir


    【解决方案1】:

    尝试以下方法:

    class POC(Entity):
      # ...
      #declare the one-to-many relationships
      csas = OneToMany('SSP')
      actions = OneToMany('SSP')
      # ...
    
    class SSP(Entity):
      # ...
      #Tell Elixir how to disambiguate POC/SSP relationships by specifying
      #the inverse explicitly.
      csa = ManyToOne('POC', colname = 'idPOCCSA', inverse='csas')
      action = ManyToOne('POC', colname = 'idPOCAction', inverse='actions')
      # ...    
    

    【讨论】:

    • 完美运行,我使用的是逆 OneToOne() 关系,没想到将其应用于 OneToMany()。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-18
    • 2010-10-22
    • 2022-11-17
    • 2020-12-23
    • 2017-03-24
    • 2010-11-01
    • 2010-10-09
    相关资源
    最近更新 更多