Generating hybrid properties automatically from SQLAlchemy Mixins

In SQLAlchemy, I would like to have a class that automatically creates hybrid properties to display attributes from a specific child table. Consider this structure:

class Address(Model):
    id = Column(Integer, primary_key=True)
    street = Column(String)
    number = Column(Integer)
    valid_from = Column(DateTime)
    valid_to = Column(DateTime)
    person_id = Column(Integer, ForeignKey('person.id'))
    person = relationship('Person', backref=backref('addresses', lazy='dynamic')

class Person(db.Model, HybridPropertyGeneratorMixin):

    data_class = Address

    id = Column(Integer, primary_key=True)

    @property
    def current_address(self):
        return self.addresses.order_by(desc(Address.valid_from))[0]

    @hybrid_property
    def city(cls):
        return self.current_address.city

    @city.expression
    def city(cls):
        return select([Address.name]). \
        where(cls.id==Address.person_id). \
        where(Address.valid_to == None).as_scalar()

      

What I'm trying to do is define a mixin that will automatically look at the data_class attributes and generate hybrid attributes and expressions from the data_class attributes. For example, I want to automatically detect a hybrid property and expression for city, state, street, etc.

UPDATE It wasn't clear enough what I originally wanted to do. See above for an update on why I want to automatically generate hybrid properties and expressions.

+3


source to share


1 answer


You can override a custom method __getattr__

to get an attribute from current_address

if it is not an attribute person

.



class Person(db.Model):
    # ...

    def __getattr__(self, item):
        return getattr(self.current_address, item)

      

0


source







All Articles