SQLAlchemy context-sensitive function to create a composite value when inserting and updating

I'm trying to figure out how to add a context-sensitive function (e.g. def get_user_full_name ()) that will be called from the standard and onupdate specifications in a column. I am trying to set a compound field that combines the first and last names into one full name to avoid having to constantly concatenate two fields in all queries.

I use a declarative approach. This is an example of a similar model:

class SomeMembers(Base):
    __tablename__ = 'some_members'
    __table_args__ = {'mysql_engine':'InnoDB'}

    SomeGroup = Column(Unicode(50), primary_key=True)
    UserID = Column(Unicode(50), primary_key=True)
    FullName = Column(Unicode(255), default=get_user_full_name, onupdate=get_user_full_name, index=True)
    FirstName = Column(Unicode(255), index=True)
    LastName = Column(Unicode(255), index=True)
    UserName = Column(Unicode(255))

This is the function I wrote, which reports in the stack trace have neither the FirstName nor LastName keys:

def get_user_full_name(context):
    return " ".join((context.compiled_parameters[0]['FirstName'],context.compiled_parameters[0]['LastName']))

, (FirstName LastName) , . , John Doe, get_user_full_name "John" "Doe" "John Doe".

context.current_parameters, . , , . , get_user_full_name :

def get_user_full_name(context):
    return " ".join((context.current_parameters['FirstName'],context.current_parameters['LastName']))

, , , , , , , .

. .

...

,

+3
1

:

from sqlalchemy.sql.expression import column, literal, literal_column

Column('full_name', String, onupdate=literal_column("first_name") + literal(" ") + literal_column("last_name"))

, full_name first_name last_name. column .

composite?

0

Source: https://habr.com/ru/post/1763381/


All Articles