Search code examples
pythonsqlalchemyhybrid

SQLAlchemy how to sets key attribute of hybrid_property


I'm using a hybrid_property to combine or manipulating column value. And i want to get a 'key' attribute of this hybrid_property columns. Here the code.

class Foo(Base):

    name = Column(String)
    address = Column(String)
    city = Column(String)

    @hybrid_property
    def full_address(self):

        return '{}, {}'.format(self.address, self.city)

    @full_address.expression
    def full_address(self):

        return func.str('{}, {}'.format(self.address, self.city))

and within Python Shell:

>>> fld = Foo.name
>>> fld.key
'name'
>>> fld = Foo.full_address
>>> fld.key
>>> type(fld.key)
<class 'NoneType'>

how to get fld.key is a 'full_address'?


Solution

  • Finally i've got the answer

    @hybrid_property def full_address(self): if isinstance(self, Foo): return '{}, {}'.format(self.address, self.city) else: return Column('full_address', String)