Insert a fixed process after SELECT with SQLAlchemy

I was wondering where to write the post-processing such as SELECTing something and then processing it for display in SQLAlchemy.

Until now, the SELECT-based self-made method was supported by explicitly attaching a self-made decorator for post-processing. But with this, if you use relationship or something and it is SELECTed in addition to some other table, it will not go through the post-processing self-made logic. Obviously. Please be amazing.

Instead, I want to be sure to execute the process as soon as it is SELECTed, no matter what the circumstances.

I wondered if Rails had something like after_find, something similar to an event in SQLAlchemy, but I did a little research, but I couldn't find anyone doing it, and eventually summer was autumn and all the cicadas died. In mourning, I finally lifted my weight and checked the official page.

Well, is it a load event that is close?

test.py


class Tests(ModelsBase, Base):
    __tablename__ = 'test'
    id = Column(Integer, primary_key=True)
    name = Column(Text)
    status = Column(SmallInteger, server_default='1')
    insert_date = Column(DateTime, server_default=func.now())
    update_date = Column(DateTime, server_default=func.now(), onupdate=func.current_timestamp())

    def __repr__(self):
        return '<Tests id:{0}, name:{1}>'.format(self.id, name)


def tests_load_listener(target, context):
	#target is an instance of Tests.
    #Processing for display, attribute generation
    if target.name:
		target.name_for_disp = target.name + 'Mr'
    else:
		target.name_for_disp = 'Nanashi-kun'

event.listen(Tests, 'load', tests_load_listener)

Most of the time, the number of selected events will occur, so if you don't think about it, you'll die, but I'm satisfied.

Besides load, there is also refresh, which is called every time there is a change in the attribute, so if you also add this, it may be cool like this, it will be ready immediately after UPDATE. ..

There were many other events. http://docs.sqlalchemy.org/en/latest/orm/events.html

That's it.

Recommended Posts

Insert a fixed process after SELECT with SQLAlchemy
How to convert a class object to a dictionary with SQLAlchemy
How to insert a specific process at the start and end of spider with scrapy