I have some SQLAlchemy models for example:
class Objects(Base):
__tablename__ = "objects"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
type: Mapped[int] = mapped_column(Integer, nullable=False)
name: Mapped[str] = mapped_column(VARCHAR(128), nullable=False)
device: Mapped["Devices"] = relationship(back_populates="object")
class Devices(Base):
__tablename__ = 'devices'
id: Mapped[int] = mapped_column(Integer, ForeignKey('objects.id'), primary_key=True)
settings: Mapped[dict] = mapped_column(JSONB)
state: Mapped[dict] = mapped_column(JSONB)
type: Mapped[int] = mapped_column(Integer, nullable=False)
object: Mapped["Objects"] = relationship(back_populates="device")
So, this is one-2-one relation. In Devices I store more concretly data about device. I need to get full info from Objects and only state from Devices. Thats not trouble. The problem is that i want to access result like this:
res.id - Objects.id
res.device.state - Devices.state
res.type - Objects.type
…
But query gives me tuple of (Objects, Devices.state). If i try joinedload or subqueryload – i`m getting not only state from DB, but settings too, I dont need them. So, help me please with sqlalchemy query, I dont know what to do.
What I want:
result: {
"id": Objects.id,
"type": Objects.type,
"name": Objects.name,
"device": {
"state": Devices.state (Objects.device.state),
"settings": None,
"type": None,
...
}
}
What I have:
result: (
{
"id": Objects.id,
"type": Objects.type,
"name": Objects.name
},
Devices.state
)
What i did:
sql = (
select(Objects, Devices.state.label("device_state"))
.join(Devices)
.filter(Objects.id == device_id)
)
sql = (
select(Objects, Devices.state)
.join_from(Objects, Devices)
.filter(Objects.id == device_id)
)
And many other attemptions, which i`ve deleted)
Кирилл Романенко is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.