【问题标题】:Elixir (SqlAlchemy): relations between 3 tables with composite primary keysElixir(SqlAlchemy):具有复合主键的 3 个表之间的关系
【发布时间】:2010-10-24 13:32:41
【问题描述】:

我有 3 张桌子:

  • 带有 (company_id) 主键的 Company 表
  • 带有(company_id, url) 主键和外键返回公司的页表
  • 带有(company_id, attr_key) 主键和返回公司的外键的 Attr 表。

我的问题是如何使用 Attr 中的现有列(即 company_idurl)构建从 Attr 到 Page 的 ManyToOne 关系?

from elixir import Entity, has_field, setup_all, ManyToOne, OneToMany, Field, Unicode, using_options
from sqlalchemy.orm import relation

class Company(Entity):
    using_options(tablename='company')
    company_id = Field(Unicode(32), primary_key=True)
    has_field('display_name', Unicode(255))
    pages = OneToMany('Page')

class Page(Entity):
    using_options(tablename='page')
    company = ManyToOne('Company', colname='company_id', primary_key=True)
    url = Field(Unicode(255), primary_key=True)

class Attr(Entity):
    using_options(tablename='attr')
    company = ManyToOne('Company', colname='company_id', primary_key=True)
    attr_key = Field(Unicode(255), primary_key=True)
    url = Field(Unicode(255)) #, ForeignKey('page.url'))
    # page = ManyToOne('Page', colname=["company_id", "url"])
    # page = relation(Page, backref='attrs', foreign_keys=["company_id", "url"], primaryjoin=and_(url==Page.url_part, company_id==Page.company_id))

我已经注释掉了一些失败的尝试。

最后,Attr.company_id 需要成为 Page 和 Company 的外键(以及 Attr 中的主键)。

这可能吗?

【问题讨论】:

    标签: python sqlalchemy python-elixir


    【解决方案1】:

    是的,您可以这样做。 Elixir 没有内置的方法来做到这一点,但因为它是 SQLAlchemy 上的一个薄包装器,你可以说服它这样做。因为 Elixir 没有重用现有列的多对一关系的概念,所以您需要将 GenericProperty 与 SQLAlchemy 关系属性一起使用,并使用表选项添加外键。下面的代码应该做你想做的:

    from elixir import Entity, has_field, setup_all, ManyToOne, OneToMany, Field, Unicode, using_options, using_table_options, GenericProperty
    from sqlalchemy.orm import relation
    from sqlalchemy import ForeignKeyConstraint
    
    class Company(Entity):
        using_options(tablename='company')
    
        company_id = Field(Unicode(32), primary_key=True)
        display_name = Field(Unicode(255))
        pages = OneToMany('Page')
    
    class Page(Entity):
        using_options(tablename='page')
    
        company = ManyToOne('Company', colname='company_id', primary_key=True)
        url = Field(Unicode(255), primary_key=True)
        attrs = OneToMany('Attr')
    
    class Attr(Entity):
        using_options(tablename='attr')
    
        page = ManyToOne('Page', colname=['company_id', 'url'], primary_key=True)
        attr_key = Field(Unicode(255), primary_key=True)
    
        using_table_options(ForeignKeyConstraint(['company_id'], ['company.company_id']))
        company = GenericProperty(relation(Company))
    

    【讨论】:

      猜你喜欢
      • 2012-05-18
      • 1970-01-01
      • 1970-01-01
      • 2015-02-15
      • 2012-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-25
      相关资源
      最近更新 更多