2

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?

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

1 Comment

Great! Also add the import from sqlalchemy.ext.hybrid import hybrid_property and rename the column so that it isn't called _roles in db _roles = db.Column("roles", db.String(255), nullable=False, default="[]", server_default="[]")

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.