Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return two SqlAlchemy Columns concatenated

I am using Flask and SQLAlchemy. I have a Person model and I want an attribute which returns the Person's full name (first + last).

I tried using @declared_attr, but it outputs:

"person.first_name || :param_1 || person.last_name"

Here is my code:

class Person(Base):
    __tablename__ = 'person'

    id = Column(Integer, primary_key = True)
    type = Column(String(50))
    first_name = Column(String(120), index = True)
    last_name = Column(String(120), index = True)

    @declared_attr
    def name(cls):
        "Returns Person's full name."
        return cls.first_name + ' ' + cls.last_name
like image 752
Binary Alchemist Avatar asked Apr 15 '14 01:04

Binary Alchemist


People also ask

How do I join two columns in SQLAlchemy?

How do I join two columns in SQLAlchemy? Python Flask and SQLAlchemy ORM Effect of joining is achieved by just placing two tables in either the columns clause or the where clause of the select() construct. Now we use the join() and outerjoin() methods.

What is returned by SQLAlchemy query?

It returns an instance based on the given primary key identifier providing direct access to the identity map of the owning Session. It creates a SQL JOIN against this Query object's criterion and apply generatively, returning the newly resulting Query. It returns exactly one result or raise an exception.

What is all () in SQLAlchemy?

method sqlalchemy.orm.Query. all() Return the results represented by this Query as a list. This results in an execution of the underlying SQL statement. The Query object, when asked to return either a sequence or iterator that consists of full ORM-mapped entities, will deduplicate entries based on primary key.

What is SQLAlchemy aliased?

The alias in SQL corresponds to a “renamed” version of a table or SELECT statement, which occurs anytime you say “SELECT * FROM table1 AS a”. The AS creates a new name for the table. Aliases allow any table or subquery to be referenced by a unique name.


2 Answers

@davidism suggested using hybrid extension, whilst I say, why not use SQLAlchemy's column_property function?

Example:

class User(Base):
    __tablename__ = 'user'
    id = Column(Integer, primary_key=True)
    firstname = Column(String(50))
    lastname = Column(String(50))
    fullname = column_property(firstname + " " + lastname)
like image 160
Alex Avatar answered Oct 17 '22 21:10

Alex


Use the hybrid extension:

from sqlalchemy.ext.hybrid import hybrid_property

class Person(Base):
    # ...
    @hybrid_property
    def name(self):
        return '{0} {1}'.format(self.first_name, self.last_name)

    @name.setter
    def name(self, value):
        self.first_name, self.last_name = value.split(' ', 1)

    @name.expression
    def name(cls):
        return db.func.concat(cls.first_name, ' ', cls.last_name)
like image 40
davidism Avatar answered Oct 17 '22 21:10

davidism