问题
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:
It looks like you're using with_entities()
to only get the User's first_name
property where the User.id == 1
, which means the result you get in user
is not a User
object but a SQLAlchemy result
type object.
Also, the reason you can't query on the slug
property is because it's a property that exists for the Python class, and not as a column in your database table.
I've never used slugify
before, but it seems that your slug
property is calculated anyway based on the first and last name.
Perhaps you can rewrite your query to filter by the first_name
and last_name
.
user = User.query.filter(User.first_name != '', User.last_name == '').filter_by(id=1).first()
Also, I think it would be helpful to define your model with a default value for certain properties:
class User(Model):
id = Column(Integer, primary_key=True)
first_name = Column(String, default='')
last_name = Column(String, default='')
...
来源:https://stackoverflow.com/questions/32019788/returning-custom-property-using-with-entities-in-flask-sqlalchemy