Reputation: 964
I'm using this model in Flask-rest with sqlalchemy in python3.5
class UserModel(db.Model):
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
username = db.Column(db.String(255), unique=True, nullable=False)
password = db.Column(db.String(600), nullable=False)
roles = db.Column(db.String(255), nullable=False)
I want to save in roles a string in json with a list of strings (the roles). I would like to access this attribute as if it were a python list and not a string (but save it in database as a string, a json list).
Non acceptable options:
1) I could make the conversion from and to database using getters and setters, but it's not what I'm looking for. It's strange to access every attribute directly except for the roles with getters and setters.
2) Make it a relation with another table of roles. I want to keep the number of tables at minimum.
Is there a way to add a method/something to add this process of transforming from and to json automatically when retrived from and saved to database?
Upvotes: 2
Views: 2610
Reputation: 337
How about using a hybrid property?
import json
from sqlalchemy.ext.hybrid import hybrid_property
class UserModel(db.Model):
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
username = db.Column(db.String(255), unique=True, nullable=False)
password = db.Column(db.String(600), nullable=False)
_roles = db.Column('roles', db.String(255), nullable=False, default='[]', server_default='[]')
@hybrid_property
def roles(self):
return json.loads(self._roles)
@roles.setter
def roles(self, roles):
self._roles = json.dumps(roles)
Edit: Added changes suggested by @monstercode
Upvotes: 4