Returning custom property using with_entities() in flask-sqlalchemy?

时间:2015-08-14 23:00:26

标签: python flask sqlalchemy flask-sqlalchemy

I have a custom property on my model. I'm using with_entities() to restrict what is returned on my model. For example,

class User(Model):
    id = Column(Integer, primary_key=True)
    first_name = Column(String)
    last_name = Column(String)

    @property
    def slug(self):
       return slugify(self.first_name + ' ' + self.last_name)

How can I return my model that only has first_name and slug?

This throws an error:

# Try with User.slug
user = User.query.with_entities(User.first_name, User.slug).filter_by(id=1).first()

>> InvalidRequestError: SQL expression, column, or mapped entity expected - got '<property object at 0x7fdac5483578>'


# Without User.slug
user = User.query.with_entities(User.first_name).filter_by(id=1).first()
print user.slug

>> AttributeError: 'result' object has no attribute 'slug'

1 个答案:

答案 0 :(得分:1)

您似乎正在使用with_entities()仅获取用户first_name的{​​{1}}属性,这意味着您在{{1}中获得的结果}}不是User.id == 1对象,而是SQLAlchemy user类型对象。

此外,您无法在User属性上查询的原因是因为它是Python类的属性,而不是数据库表中的列。

我之前从未使用过result,但似乎您的slug属性仍然是根据姓名计算的。

也许您可以根据slugifyslug重写您的查询以进行过滤。

first_name

另外,我认为使用某些属性的默认值定义模型会很有帮助:

last_name