Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to access joined table values in a right way? #506

Open
DenysMoskalenko opened this issue Aug 10, 2022 · 1 comment
Open

How to access joined table values in a right way? #506

DenysMoskalenko opened this issue Aug 10, 2022 · 1 comment

Comments

@DenysMoskalenko
Copy link

DenysMoskalenko commented Aug 10, 2022

The problem is in accessing attributes after tables join.

So my models are next:

class Itinerary(Base):
    __tablename__ = 'itineraries'

    id = Column(Integer, primary_key=True)
    name = Column(String(128))
    bus_id = Column(Integer, ForeignKey('buses.id'), nullable=False)

class Bus(Base):
    __tablename__ = 'buses'

    id = Column(Integer, primary_key=True)
    name = Column(String(128), nullable=False)
    number_plate = Column(String(16), nullable=False, unique=True, index=True)

The Pydantic models:

class ItinerarySchema(BaseModel):
    id: inty
    name: str
    bus: BusSchema


class BusSchema(BaseModel):
    id: int
    name: str
    number_plate: str

Also the function to get itinerary:

async def get_itinerary_by_id(db: Database, itinerary_id: int) -> ItinerarySchema:
    query = select(Itinerary, Bus).join(Bus).filter(Itinerary.id == itinerary_id)
    itinerary = await db.fetch_one(query=query)

    bus = BusSchema(
        id=itinerary.id_1,  # <- HERE is the problem
        name=itinerary.name_1,  # <- HERE is the problem
        number_plate=itinerary.number_plate,
    )

    return ItinerarySchema(id=itinerary['id'], name=itinerary['name'], bus=bus)

It's works, but looks weird. Could you pls describe how I can access to the attributes in a more right way than *.id_1 and *.name_1

@berkio3x
Copy link

@DenysMoskalenko I guess, the concern of alias names for id and name etc.. is more related to the query builder , in this case sqlalchemy.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants