[英]Querying for a particular subclass(child) in an inheritance will render the base class(parent) attributes in addition to the subclass attributes
我是sqlalchemy-ORM的新手,我不知道要在代碼中添加些什么,以使子表看到父表的屬性及其自身的屬性。
我正在使用sqlalchemy-ORM創建數據庫。我在“設備”表(基類),“集線器”和“控制器”(子類)之間進行了聯接表繼承。 默認情況下,基類會看到其自身和子類的屬性,但是如果我想反過來怎么辦。 我的問題是代碼中的子類只能看到其自身的屬性,而我希望它既可以看到父級又可以看到其自身的屬性。
class Device(Base):
__tablename__ = "device"
id = Column('id' , Integer , primary_key=True)
name = Column('name' , String)
status = Column('status', Boolean)
room_id = Column(Integer , ForeignKey('room.id'))
type = Column('type' , String)
__mapper_args__ = {'polymorphic_identity':'device', 'polymorphic_on': type
}
class Hub(Device):
__tablename__ = "hub"
id = Column('id' ,Integer , ForeignKey('device.id'), primary_key=True)
__mapper_args__ = {'polymorphic_identity':'hub'
}
class Controller(Device):
__tablename__ = "controller"
id = Column('id' , Integer , ForeignKey('device.id'), primary_key=True)
__mapper_args__ = {'polymorphic_identity':'controller'
}
您似乎想做的就是將大多數信息存儲在Device對象上,然后通過將其鏈接到稱為Hub和Controller的單獨表中的記錄來區分它們。 例如,如果您有2個控制器和1個集線器:
===============================================
Table: "device"
id name status room_id type
===============================================
1 Hub A True 1 Hub
2 Troller A True 1 Troll
3 Troller B False 8 Troll
===============================================
============
Table: "hub"
id
============
1
============
===================
Table: "controller"
id
===================
2
3
===================
盡管在其他情況下類似的事情可能很有意義,但它沒有利用您正在使用的關系數據庫。 相反,我只建議所有設備使用一個表,然后將它們鏈接到第二個設備類型表:
class Device(Base):
__tablename__ = 'device'
id = Column(Integer, primary_key=True)
name = Column(String)
status = Column(Boolean)
room_id = Column(Integer, ForeignKey('room.id')
type_id = Column(Integer, ForeignKey('device_type.id')
type = relationship('DeviceType', backref='devices')
class DeviceType(Base):
__tablename__ = 'device_type'
id = Column(Integer, primary_key=True)
name = Column(String)
不要忘記from sqlalchemy.orm import relationship
。 這樣,您可以選擇一種類型,然后使用關系來獲取該類型的所有設備。 您將來也可以添加新的設備類型,而不必添加全新的表。
在這種情況下,上面的相同表格將顯示為:
===============================================
Table: "device"
id name status room_id type_id
===============================================
1 Hub A True 1 1
2 Troller A True 1 2
3 Troller B False 8 3
===============================================
====================
Table: "device_type"
id name
====================
1 Hub
2 Controller
====================
如果要返回所有控制器的列表,只需查詢控制器device_type
並使用關系/ backref並獲取所有關聯的設備:
controller_type = session.query(DeviceType).get(2)
controllers = controller_type.devices
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.