I use Flask-SQLAlchemy + Flask-Migrate as my database for my website. I prefer declarative style, because I end up with a class, an actual entity that has attributes that I specified:
class user(db.Model):
# some fields...
skills = mapped_column(JSON)
The db and migrations themselves work perfectly fine, the problem is that in each request I have to manually manipulate input (i.e. http request) into output (i.e. changing row values or creating new instance etc.). Abstract:
@app.route(...)
def update_user_skills(user, desired_skills): # user is acquired via execute(select(...))
# and desired_skills is from request arguments
# some complex validation logic that doesn't
# really belong in the request function...
if array_valid:
user.skills = desired_skills
db.session.commit()
return ('', 200) # success response
The problem with this code is that most of the code is not really related to the request itself, it’s more of the model part, from the MVC standpoint. I would like to move this part to the user
class as that’s where the actual fields attributes exist:
class user(db.Model):
# some fields...
skills = mapped_column(JSON)
def update_skills(self, desired_skills):
# validate desired_skills...
if array_valid:
self.skills = desired_skills
But I am afraid this is going to mess up with the SQLAlchemy part of the user
class. In short, is there any side effects of adding some functionality to the declarative db class? Won’t that interfere with migrations or with sqlalchemy itself?