4

I am trying to build a User model for python. I have to insert values into a a database using SQL_Alchemy ORM. For this I have defined a class User which has attributes id,first_name,second_name,last_name,email etc. The class inherits the db.Model and the attirbutes and coloumns are mapped accordingly. The implementation of the class is given below:

class Users(db.Model):
    __tablename__ = 'users'
    id = db.Coloumn('id',db.Integer,primary_key=True)
    first_name = db.Coloumn('first_name',db.String)
    second_name = db.Coloumn('second_name',db.String)
    last_name = db.Coloumn('last_name',db.String)
    email = db.Coloumn('email',db.String)
    password = db.Coloumn('password',db.String)

I want to implement a method name insert() which takes value as an argument and maps it to the class attributes dynamically.

For now I have implemented it the following way:

    def insert(self,first_name,second_name,last_name,email,password):
        self.first_name = first_name
        self.second_name = second_name
        self.last_name = last_name
        self.email = email
        self.password = password

I want to implement the method in such a way that dictionary values as an kwargument and maps it to the the class attributes accordingly.

For example the method should be declared as insert(self,**kwargs):

davidism
  • 121,510
  • 29
  • 395
  • 339
D14TEN
  • 337
  • 6
  • 15

1 Answers1

4

There are two ways. More verbosely:

def insert(self, **kwargs):
    for k, v in kwargs.items():
        setattr(self, k, v)

Or, more succinctly:

def insert(self, **kwargs):
    self.__dict__.update(kwargs)

The latter won't work for classes whose instances don't have __dict__'s, like classes that define __slots__

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172