Unable to call the "list" object when using Session.add_all [closed]

1

I am inconvenienced with this code generates me error:

  

id_ccf = input ("Type the name of the CCF"))])
  TypeError: 'list' object is not callable

I do not understand why, I do not have any object named 'list'. This is the relevant part of my code:

def Agregar():
    Empleados = []
    Session = sessionmaker(bind=eng)
    session = Session()

    session.add_all([
        Empleados(numdocEmp = input("Digite el numero de Documento del Empleado"),
                  tipodocEmp = input("Digite el tipo de Documento del Empleado"),
                  nombre1Emp = input("Digite el primer nombre del empleado"),
                  nombre2Emp = input("Digite el segundo nombre del empleado"),
                  apell1Emp = input("Digite el primer apellido del empleado"),
                  apell2Emp = input("Digite el segundo apellido del empleado"),
                  fechaingEmp = input("Digite la fecha de ingreso del empleado"),
                  cargoEmp = input("Digite el cargo  del empleado"),
                  tipocontEmp = input("Digite el tipo de contrato del empleado"),
                  sbmEmp = input("Digite el salario basico mes del empleado"),
                  fotoEmp = input("foto del empleado"),
                  id_eps = input("Digite el nombre de La EPS"),
                  id_afp = input("Digite el nombre de la AFP"),
                  id_arl = input("Digite el nombre de la ARL"),
                  id_ccf = input("Digite el nombre de la CCF"))])

    session.commit()
    session.close()

Edit:

According to the comments I tried to create my class Empleados with the following structure:

class Empleados(Base):
    __tablename__ = 'empleados'

    id_Emp = Column(Integer(), primary_key=True)
    numdocEmp = Column(Integer()
    ....


    def __init__(self):
        self.id_Emp = 0
        self.numdocEmp = 0
        self.tipodocEmp = 0
        .....


    def __repr__(self)
        return "<Empleados(numdocEmp = '%s', tipodocEmp = '%s'.............
                      " % (self.numdocEmp, self.tipodocEmp,....

But now I get the following error:

  

TypeError: __init __ () got an unexpected keyword argument 'id_arl'

    
asked by Jsierra2017 14.12.2017 в 01:45
source

1 answer

1

The original error is because Empleados is a Python list and you try to call it when doing:

session.add_all([Empleados(numdocEmp...),...])

You must have a class Empleado to be able to create objects that will be appropriately mapped in the corresponding table of your database.

Created this class we can instantiate all the objects that we want and create the appropriate rows in the table using a session by Session.add(<Instancia de Empleado>) or adding several objects at the same time with Session.add_all([<Instancia de Empleado1>,<Instancia de Empleado2>, ...]) .

The classes mapped using the Declarative System are defined within a base class that maintains a catalog of classes and tables related to that base. As a general rule, this instance of the base class will be unique in the app and is created by instantiating sqlalchemy.ext.declarative.declarative_base . In this case this class could be something like this:

Base = declarative_base()

class Empleado(Base):
    __tablename__ = 'empleados'

    id_Emp = Column(Integer, primary_key=True)
    numdocEmp = Column(Integer)
    tipodocEmp = Column(Integer)
    nombre1Emp = Column(String)
    # Resto de columnas con sus tipos apropiados.

In the definition of the table (class Empleado ) it is not necessary in principle to use an initializer ( __init__ ) explicitly using the current declarative system, if one is not provided explicitly, the class will automatically accept arguments to the be instantiated but they will always be of type key-word (coinciding with the names of the columns defined as class attributes), they can never be positional.

If we want or need to include our own initializer, it overwrites the previous one. It must receive as arguments those attributes (value of each column) that we want to pass when initializing and the initialized attributes in it must match the name of the columns declared as class attributes before.

The error you have after editing is due to the fact that in the definition of your __init__ you do not receive any parameter but then you try to pass the values of the columns when initializing the class. To use your own initializer you must do something as shown in the example below.

Based on the example of the question (the table has only 4 columns for not making the code too extensive) we can see a fully reproducible example using sqlite :

from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String
from sqlalchemy.orm import sessionmaker

engine = create_engine('sqlite:///myexampledb.db', echo=True)
Base = declarative_base()

class Empleado(Base):
    __tablename__ = 'empleados'

    id_Emp = Column(Integer, primary_key=True)
    numdocEmp = Column(Integer)
    tipodocEmp = Column(Integer)
    nombre1Emp = Column(String)

    def __init__(self, numdocEmp, tipodocEmp,  nombre1Emp): # <<<<<
        self.numdocEmp = numdocEmp
        self.tipodocEmp = tipodocEmp
        self.nombre1Emp = nombre1Emp


    def __repr__(self):
        repr_str = "<Empleado(numdocEmo={}, tipodecEmp={}, nombre1Emp={})>"
        return repr_str.format(self.numdocEmp,
                               self.tipodocEmp,
                               self.nombre1Emp)

# Creamos la tabla
Base.metadata.create_all(engine)

#Creamos la sesión
Session = sessionmaker(bind=engine)
session = Session()

# Añadir un empleado
session.add(Empleado(numdocEmp = 10, tipodocEmp = 1,  nombre1Emp = "Rafael"))

# Añadir varios empleados
empleados = [Empleado(numdocEmp = 14, tipodocEmp = 1,  nombre1Emp = "Luis"), 
             Empleado(numdocEmp = 15, tipodocEmp = 2,  nombre1Emp = "Maria"), 
             Empleado(numdocEmp = 16, tipodocEmp = 3,  nombre1Emp = "Elena")]
session.add_all(empleados)

session.commit()

# Mostramos todos los objetos empleado de la tabla.
res = session.query(Empleado).all()
for empleado in res:
    print(empleado)
    
answered by 15.12.2017 в 23:06