表(模型)用Flask SQLAlchemy继承 [英] Table(Model) Inheritance with Flask SQLAlchemy

查看:1025
本文介绍了表(模型)用Flask SQLAlchemy继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遵循这个问题的建议,但是我仍然收到这个错误:
sqlalchemy.exc.NoForeignKeysError:在'投资'和'real_estate'之间找不到任何外键关系。



模特 $ b <$ p $投资(db.Model):

__tablename__ ='投资'
__mapper_args__ = {'polymorphic_identity':'投资'}

id = Column(db.Integer,primary_key = True)
item_name = Column(db.String(64))
investment_type = Column(db.String(32),nullable = False)
__mapper_args__ = {'polymorphic_on':investment_type}
$ b $ class RealEstate(投资):

__tablename__ ='real_estate'
__mapper_args__ = {'polymorphic_identity':' (db.teger,primary_key = True)
current_balance = Column(db.Float)

我也更新了这个答案中的例子,以反映SQLAlchemy的文档中的变化,但仍然是错误。 目标这里是我不希望由RealEstate继承的属性在投资表。我想继承和保留RealEstate表的所有这些属性。

任何人都可以看到我错过了什么?

id 属性必须是引用投资的外键。否则,你怎么能说每个RealEstate都是一项投资?



将您的RealEstate类定义更改为以下内容:

  class RealEstate (投资):

__tablename__ ='real_estate'
__mapper_args__ = {'polymorphic_identity':'real_estate'}
#下面的id应该引用Investment。因此,将其定义为外键。
id = Column(Integer,ForeignKey('investment.id'),primary_key = True)
current_balance = Column(db.Float)


I followed the advice in this question but I'm still receiving this error: sqlalchemy.exc.NoForeignKeysError: Can't find any foreign key relationships between 'investment' and 'real_estate'.

Models

class Investment(db.Model):

    __tablename__ = 'investment'
    __mapper_args__ = {'polymorphic_identity': 'investment'}

    id = Column(db.Integer, primary_key=True)
    item_name = Column(db.String(64))
    investment_type = Column(db.String(32), nullable=False)
    __mapper_args__ = {'polymorphic_on': investment_type}

class RealEstate(Investment):

    __tablename__ = 'real_estate'
    __mapper_args__ = {'polymorphic_identity': 'real_estate'}
    id = Column(db.Integer, primary_key=True)
    current_balance = Column(db.Float)

I also updated the examples in that answer to reflect changes in SQLAlchemy's docs but, still, the error.

The goal here is that I don't want the attributes inherited by RealEstate to be in the Investment table. I would like to inherit and retain all of these attributes with the RealEstate table.

Can anyone see what I missed?

解决方案

The id attribute in RealEstate must be a foreign key referencing the Investment. Otherwise, how can you say that every RealEstate is an investment ?

Change your RealEstate class definition to the following:

class RealEstate(Investment):

__tablename__ = 'real_estate'
__mapper_args__ = {'polymorphic_identity': 'real_estate'}
# This id below should reference Investment. Hence, define it as foreign key. 
id = Column(Integer, ForeignKey('investment.id'), primary_key=True)
current_balance = Column(db.Float)

这篇关于表(模型)用Flask SQLAlchemy继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆