简体   繁体   中英

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'?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM