我有三张桌子:
(company_id)主键(company_id, url)主键的页面表和一个返回(company_id, attr_key)主键的Attr表和一个返回公司的外键。F 210
我的问题是如何利用Attr中现有的列,即ManyToOne和url,构建从Attr到页面的Attr关系?
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将需要成为页和公司的密钥(同时也是Attr的主密钥)。
这个是可能的吗?
发布于 2009-05-14 23:34:12
是的你能做到的。灵丹妙药没有一个内置的方法来实现这一点,但是因为它是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))https://stackoverflow.com/questions/835834
复制相似问题