Add sub-component support via self-referential device hierarchy
This commit is contained in:
@@ -32,6 +32,7 @@ class Device(Base):
|
||||
location = Column(String(100), nullable=True)
|
||||
notes = Column(Text, nullable=True)
|
||||
ha_entity_id = Column(String(100), nullable=True) # e.g. "sensor.tv_remote_battery"
|
||||
parent_id = Column(Integer, ForeignKey("device.id", ondelete="SET NULL"), nullable=True)
|
||||
|
||||
batteries = relationship("Battery", back_populates="device")
|
||||
logbook_entries = relationship(
|
||||
@@ -40,6 +41,20 @@ class Device(Base):
|
||||
cascade="all, delete-orphan",
|
||||
single_parent=True,
|
||||
)
|
||||
parent = relationship(
|
||||
"Device",
|
||||
back_populates="children",
|
||||
primaryjoin="Device.parent_id == Device.id",
|
||||
foreign_keys="[Device.parent_id]",
|
||||
remote_side="[Device.id]",
|
||||
)
|
||||
children = relationship(
|
||||
"Device",
|
||||
back_populates="parent",
|
||||
primaryjoin="Device.parent_id == Device.id",
|
||||
foreign_keys="[Device.parent_id]",
|
||||
order_by="Device.name",
|
||||
)
|
||||
|
||||
def installed_count(self):
|
||||
return sum(1 for b in self.batteries if b.status == "installed")
|
||||
@@ -50,6 +65,12 @@ class Device(Base):
|
||||
def has_mixed_brands(self):
|
||||
return len(self.installed_brands()) > 1
|
||||
|
||||
def has_children(self):
|
||||
return bool(self.children)
|
||||
|
||||
def is_subcomponent(self):
|
||||
return self.parent_id is not None
|
||||
|
||||
def __repr__(self):
|
||||
return f"<Device {self.name}>"
|
||||
|
||||
|
||||
Reference in New Issue
Block a user