使用PGModeler,我们创建了一个模式,然后导出了一些适当的SQL代码。SQL命令能够在Postgres数据库中填充适当的表和行。
从这里开始,我们希望创建声明性的Sqlalchemy模型,Sqlautocode也是如此。我们在航站楼查过了:
sqlautocode postgresql+psycopg2://username:password@host/db_name -o models.py -d它按预期生成了我们的表和相应的模型。到目前为止,没有任何错误。
然后,在使用ipython时,我从models.py导入了所有内容,并简单地尝试创建一个在那里定义的类的实例。突然,我发现了一个错误:
AttributeError: 'RelationshipProperty' object has no attribute 'c'这一次让我困惑了一段时间。讨论这一问题的其他SO线程的解决方案与我的问题完全不同(通常与特定的框架或语法不被sqlautocode使用有关)。
找到原因后,我决定把手头的问题记录下来。见下文。
发布于 2013-08-14 21:20:38
我们的问题仅仅是因为在运行sqlautocode时,变量的命名错误。具体来说,错误的命名发生在任何具有本身的外键的模型中,即。
下面是一个例子:
#Note that all \"relationship\"s below are now \"relation\"
#it is labeled relationship here because I was playing around...
service_catalog = Table(u'service_catalog', metadata,
Column(u'id', BIGINT(), nullable=False),
Column(u'uuid', UUID(), primary_key=True, nullable=False),
Column(u'organization_id', INTEGER(), ForeignKey('organization.id')),
Column(u'type', TEXT()),
Column(u'name', TEXT()),
Column(u'parent_service_id', BIGINT(), ForeignKey('service_catalog.id')),
)
#Later on...
class ServiceCatalog(DeclarativeBase):
__table__ = service_catalog
#relation definitions
organization = relationship('Organization', primaryjoin='ServiceCatalog.organization_id==Organization.id')
activities = relationship('Activity', primaryjoin='ServiceCatalog.id==ActivityService.service_id', secondary=activity_service, secondaryjoin='ActivityService.activity_id==Activity.id')
service_catalog = relationship('ServiceCatalog', primaryjoin='ServiceCatalog.parent_service_id==ServiceCatalog.id')
organizations = relationship('Organization', primaryjoin='ServiceCatalog.id==ServiceCatalog.parent_service_id', secondary=service_catalog, secondaryjoin='ServiceCatalog.organization_id==Organization.id')在ServiceCatalog.organizations中,它希望第二个表是service_catalog,但是该变量只是在本地被覆盖。改变两者的顺序将解决这个问题。
https://stackoverflow.com/questions/18242525
复制相似问题