How to select only related model?

  Kiến thức lập trình

I need to select only Phone.user when selecting Phone model:

from sqlalchemy import ForeignKey, select
from sqlalchemy import create_engine
from sqlalchemy.orm import DeclarativeBase, Session, relationship, joinedload
from sqlalchemy.orm import Mapped
from sqlalchemy.orm import mapped_column

engine = create_engine("sqlite:///:memory:", echo=True)


class Base(DeclarativeBase):
    pass


class User(Base):
    __tablename__ = "users"
    id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
    first_name: Mapped[str]
    last_name: Mapped[str]
    phones: Mapped[list["Phone"]] = relationship(back_populates="user")


class Phone(Base):
    __tablename__ = "phones"
    id: Mapped[int] = mapped_column(autoincrement=True, primary_key=True)
    phone: Mapped[str]
    user_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="cascade"))
    user: Mapped["User"] = relationship(back_populates="phones")


Base.metadata.create_all(engine)

with Session(engine) as session:
    user = User(first_name="Ivan", last_name="Ivanov")
    phone = Phone(phone="79995437264", user=user)
    session.add(phone)
    session.commit()

    stmt = select(Phone.user).options(joinedload(Phone.user))
    res = session.scalars(stmt).all()

The code above produces following SQL query:

SELECT users.id = phones.user_id AS user 
FROM users, phones

How to select Phone.user?

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website

LEAVE A COMMENT