python - loading @hybrid_property of SQLAlchemy ORM to pandas DataFrame

Viewed 96

TLDR DataFrame.from_records() ignores @hybrid_property of sqlalchemy ORM

Hello, I want to be able to populate pandas.DataFrame from sqlalchemy objects. I have a class which is defined like that:

class Cat_24(Base):
    __tablename__ = "cat_24"
    ad_id = Column(Integer, primary_key=True, unique=True)
    title = Column(String(128))
    description = Column(String(8192))
    offer_type = Column(String(16))
...
    prices = relationship("AdPrice", backref=backref("cat_24"))
...
    @hybrid_property
    def last_price(self):
        if self.prices:
            return self.prices[-1].price
        else:
            return None

    @last_price.expression
    def last_price(cls):
        # return cls.prices[-1].price
        return (
            select([AdPrice.price])
            .where(cls.ad_id == AdPrice.ad_id)
            .order_by(AdPrice.price.desc())
            .limit(1)
            .as_scalar()
        )

When I tries to select rows and load them:

tmp = session.query(Cat_24).filter_by(offer_type='Продам').all()
df = pd.DataFrame.from_records( tmp )

I can see only regular Columns in dataframe, last_price will not be loaded. So question, how to load hybrid_property in DataFrame?

Update ugly solution which I figured out:

    def __iter__(self):
        for column in self.__table__.columns:
            yield column.name, getattr(self, column.name)

        if self.aditional_attrs:
            for attr in self.aditional_attrs:
                yield attr, getattr(self, attr)

self.aditional_attrs is a tuple with hybrid_property names which I want to get, after that tmp query from the above can be converted into list of dictionaries:

tmp = list(map(dict,tmp))
0 Answers
Related