2009-10-05 46 views
0

我想要定義一個可以描述以下關係的SQLAlchemy/Elixer模型。我有一個SSP表,它有POC表的多個外鍵。我已經在SSP對象中正確定義了ManyToOne關係(允許我正確地使用SSP.get(1).action.first_name)。我還想補充的是這種關係的另一方面,我可以執行類似POC.get(1).csa之類的操作,並返回一個SSP對象列表,其中此POC被定義爲idPOCCSA。Python SQLAlchemy/Elixer問題

我知道這將是最好的多態關聯,但我真的不能改變數據庫模式(創建一個新的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參數。有點不詳細。

回答

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') 
    # ...  
+0

完美的作品,我是用逆用OneToOne()的關係,沒想到把它應用到一對多()。 – 2009-10-05 17:06:07