femtozer
femtozer

Reputation: 687

Update function for a Flask-SQLAlchemy model

I often use an update function when working with Flask-SQLAlchemy models:

from app import db


class User(db.Model):
    __tablename__ = 'User'

    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(255))
    name = db.Column(db.String(255))

    def update(self, email=None, name=None):
        if email is not None:
            self.email = email
        if name is not None:
            self.name = name
        
    def dump(self):
        return dict([(k, v) for k, v in vars(self).items() if not k.startswith("_")])

This allows me to directly update an object with a json body:

user.update(**body)

But with a table containing a lot of columns, writing this function can be really annoying.
Do you know a more concise approach?

Upvotes: 0

Views: 724

Answers (1)

UjinT34
UjinT34

Reputation: 4977

You can iterate over dict fields and use setattr to update:

for field, value in body.items():
    if value is not None:
        setattr(self, field, value)
   

Upvotes: 1

Related Questions