0

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?

1 Answer 1

1

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)
   
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.