7

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

2 Answers 2

9

@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)
Sign up to request clarification or add additional context in comments.

1 Comment

Yea this seems most applicable, they even use it as an example of how it's used in their docs! Cheers
6

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.