-
-
Save kjaanson/12be39198b39208aa3c3baee97a47fc7 to your computer and use it in GitHub Desktop.
Using getters and setters with SQLAlchemy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Table(Base): | |
id = Column(Integer, primary_key=True) | |
_name = Column('name', String(24)) | |
@property | |
def name(self): | |
return self._name; | |
@name.setter | |
def name(self, value): | |
self._name = value.title() | |
#A query you might perform on the table. | |
#It won't work anymore :'( | |
query = db_session.query(Table)\ | |
.filter(Table.name == 'Theron') | |
#You could do this, but it doesn't look as nice, is inconsistent with the "id" | |
#column, and you'd have to update all your existing code. | |
query = db_session.query(Table)\ | |
.filter(Table._name == 'Theron') |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from sqlalchemy.orm import synonym | |
class Table(Base): | |
id = Column(Integer, primary_key=True) | |
_name = Column('name', String(24)) | |
@property | |
def name(self): | |
return self._name; | |
@name.setter | |
def name(self, value): | |
self._name = value.title() | |
name = synonym('_name', descriptor=name) | |
#A query you might perform on the table. | |
#Now it works again! :) | |
query = db_session.query(Table)\ | |
.filter(Table.name == 'Theron') |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Table(Base): | |
id = Column(Integer, primary_key=True) | |
name = Column(String(24)) | |
#A query you might perform on the table. | |
query = db_session.query(Table)\ | |
.filter(Table.name == 'Theron') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment