Ir al contenido
Odoo Menú
  • Identificarse
  • Pruébalo gratis
  • Aplicaciones
    Finanzas
    • Contabilidad
    • Facturación
    • Gastos
    • Hoja de cálculo (BI)
    • Documentos
    • Firma electrónica
    Ventas
    • CRM
    • Ventas
    • TPV para tiendas
    • TPV para restaurantes
    • Suscripciones
    • Alquiler
    Sitios web
    • Creador de sitios web
    • Comercio electrónico
    • Blog
    • Foro
    • Chat en directo
    • e-learning
    Cadena de suministro
    • Inventario
    • Fabricación
    • PLM
    • Compra
    • Mantenimiento
    • Calidad
    Recursos Humanos
    • Empleados
    • Reclutamiento
    • Ausencias
    • Evaluación
    • Referencias
    • Flota
    Marketing
    • Marketing social
    • Marketing por correo electrónico
    • Marketing por SMS
    • Eventos
    • Automatización de marketing
    • Encuestas
    Servicios
    • Proyecto
    • Partes de horas
    • Servicio de campo
    • Servicio de asistencia
    • Planificación
    • Citas
    Productividad
    • Conversaciones
    • Aprobaciones
    • IoT
    • VoIP
    • Conocimientos
    • WhatsApp
    Aplicaciones de terceros Studio de Odoo Plataforma de Odoo Cloud
  • Industrias
    Comercio al por menor
    • Librería
    • Tienda de ropa
    • Tienda de muebles
    • Tienda de ultramarinos
    • Ferretería
    • Juguetería
    Alimentación y hostelería
    • Bar y pub
    • Restaurante
    • Comida rápida
    • Casa de huéspedes
    • Distribuidor de bebidas
    • Hotel
    Inmueble
    • Agencia inmobiliaria
    • Estudio de arquitectura
    • Construcción
    • Gestión inmobiliaria
    • Jardinería
    • Asociación de propietarios
    Consultoría
    • Empresa contable
    • Partner de Odoo
    • Agencia de marketing
    • Bufete de abogados
    • Adquisición de talentos
    • Auditorías y certificaciones
    Fabricación
    • Textil
    • Metal
    • Muebles
    • Alimentos
    • Cervecería
    • Regalos de empresas
    Salud y bienestar
    • Club deportivo
    • Óptica
    • Gimnasio
    • Terapeutas
    • Farmacia
    • Peluquería
    Oficios
    • Handyman
    • Hardware y soporte técnico
    • Sistemas de energía solar
    • Zapatero
    • Servicios de limpieza
    • Servicios de calefacción, ventilación y aire acondicionado
    Otros
    • Organización sin ánimo de lucro
    • Agencia de protección del medio ambiente
    • Alquiler de paneles publicitarios
    • Estudio fotográfico
    • Alquiler de bicicletas
    • Distribuidor de software
    Explorar todos los sectores
  • Comunidad
    Aprender
    • Tutoriales
    • Documentación
    • Certificaciones
    • Formación
    • Blog
    • Podcast
    Potenciar la educación
    • Programa de formación
    • Scale Up! El juego empresarial
    • Visita Odoo
    Obtener el software
    • Descargar
    • Comparar ediciones
    • Versiones
    Colaborar
    • GitHub
    • Foro
    • Eventos
    • Traducciones
    • Convertirse en partner
    • Servicios para partners
    • Registrar tu empresa contable
    Obtener servicios
    • Encontrar un partner
    • Encontrar un asesor fiscal
    • Contacta con un experto
    • Servicios de implementación
    • Referencias de clientes
    • Ayuda
    • Actualizaciones
    GitHub YouTube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Solicitar una demostración
  • Precios
  • Ayuda

Odoo is the world's easiest all-in-one management software.
It includes hundreds of business apps:

  • CRM
  • e-Commerce
  • Contabilidad
  • Inventario
  • PoS
  • Proyecto
  • MRP
All apps
Debe estar registrado para interactuar con la comunidad.
Todas las publicaciones Personas Insignias
Etiquetas (Ver todo)
odoo accounting v14 pos v15
Acerca de este foro
Debe estar registrado para interactuar con la comunidad.
Todas las publicaciones Personas Insignias
Etiquetas (Ver todo)
odoo accounting v14 pos v15
Acerca de este foro
Ayuda

Create multi records from one server action

Suscribirse

Reciba una notificación cuando haya actividad en esta publicación

Se marcó esta pregunta
development
1 Responder
2739 Vistas
Avatar
Ali Ammar
ValueError: : "Expected singleton: hr.salary.details(1, 2)" while evaluating
'for record in records:\n record.calculate_salary()'

my server action xml code:

 

< field name = "name" > calculate salary field > 

 

 

list field> 

code field> 

                 for record in records:

                         record.calculate_salary()

field > 

records >                                                            

my function: 

def calculate_salary(self):

         for rec in self:

             salary = []

             get_date = datetime. today (  ) 

             month = int(get_date.month ) -1_ 

             salary . append({ 'name': ('salary for') + " " + str(rec.employee1_name_id['name'])+ " " + str(month ),

                                 'employee1_name': rec. employee1_name_id [ 'name' ],

                                 'salary_id': rec.id ,

                                 'employee_number': rec. employee_number_id ,

                                 'employee_job_title': rec. employee_job_title , 

                                'employee_salary': rec . employee_salary ,

                                 'hawafez_salary': rec. hawafez_salary , 

                                'cooperation_box': rec . cooperation_box ,

                                 ':rec. total_salary ,                                

                            })

             rec. env [ 'hr.salary.months' ].create( salary )


0
Avatar
Descartar
Avatar
Malay Khamar (Serpent Consulting Services Pvt. Ltd.)
Mejor respuesta

Hi Ali Ammar,

As you are already added a loop into your function, So you can directly use the records in the server code.

Just like :

       field name="code"> records.calculate_salary()

Also at the last line , you can directly use a self instead of rec for salary month object. Just like:

                 self. env [ 'hr.salary.months' ].create( salary )

And try to defined the object in a variable outside of the loop and use that variable into the code for better code execution and performance.

I already Provide the solution for this in your previous question which was closed by you. 
Have you checked that. 

Updated Answer:

Please try with the below code 



# Server Action
record id="generate_salary" model="ir.actions.server">
field name="name">calculate salary
field name="model_id" ref="hr_salary.model_hr_salary_details"/>
field name="binding_model_id" ref="hr_salary.model_hr_salary_details"/>
field name="binding_view_types">list
field name="state">code
field name="code">
if records:
records.calculate_salary()
/field>
/record>


# Let the system take the default api
def calculate_salary(self):
salary_mnth_obj = self.env['hr.salary.months']
for rec in self:
salary_mnth_obj.create({
'name': ('salary for') + " " + str(rec.employee1_name_id.name),
'employee1_name': rec. employee1_name_id.name,
'salary_id': rec.id ,
'employee_number': rec.employee_number_id,
'employee_job_title': rec. employee_job_title,
'employee_salary': rec . employee_salary,
'hawafez_salary': rec. hawafez_salary,
'cooperation_box': rec . cooperation_box ,
})
return True
Hope it will help you.
2
Avatar
Descartar
Ali Ammar
Autor

I do all that you say
I still have the same error
if I delete the create method I don't have error
but when I add it and run for multi record I faced the error

Malay Khamar (Serpent Consulting Services Pvt. Ltd.)

Hi ,
Can you please try with the below code.

# Server Action
record id="generate_salary" model="ir.actions.server">
field name="name">calculate salary</field>
field name="model_id" ref="hr_salary.model_hr_salary_details"/>
field name="binding_model_id" ref="hr_salary.model_hr_salary_details"/>
field name="binding_view_types">list</field>
field name="state">code</field>
field name="code">
if records:
records.calculate_salary()
/field>
/record>

# Let the system take the default api
def calculate_salary(self):
salary_mnth_obj = self.env['hr.salary.months']
for rec in self:
salary_mnth_obj.create({
'name': ('salary for') + " " + str(rec.employee1_name_id.name),
'employee1_name': rec. employee1_name_id.name,
'salary_id': rec.id ,
'employee_number': rec.employee_number_id,
'employee_job_title': rec. employee_job_title,
'employee_salary': rec . employee_salary,
'hawafez_salary': rec. hawafez_salary,
'cooperation_box': rec . cooperation_box ,
})
return True

Hope it will help you.

Malay Khamar (Serpent Consulting Services Pvt. Ltd.)

Hi Ali Ammar,
Please check the updated answer. I hope it will help you.

Ali Ammar
Autor

raise exception.with_traceback(None) from new_cause
ValueError: <class 'ValueError'>: "Expected singleton: hr.salary.details(1, 2, 3)" while evaluating
'if records:\n records.calculate_salary()'

after I run your code

Malay Khamar (Serpent Consulting Services Pvt. Ltd.)

Then you must be check the code for the create and compute methods of the model "hr.salary.months" and the api decorators for those methods.
I hope it will help you.

Ali Ammar
Autor

the problem in create method and I don't know how to solve

Malay Khamar (Serpent Consulting Services Pvt. Ltd.)

Please share the create method.
Thanks

Ali Ammar
Autor

I didn't write any thing else over the above code
create method still like itself

Malay Khamar (Serpent Consulting Services Pvt. Ltd.)

Ok , then try to add a create method in the model and check the result. Hope it will help you.

Ali Ammar
Autor

What should I write in this method?

Ali Ammar
Autor

I solve singleton error
thanx
but now it's create only the first record in my selected records as much i select records

Malay Khamar (Serpent Consulting Services Pvt. Ltd.)

Please print the self into your code and check if it takes the multiple records or not.
User active_ids from the context instead of the self.
Hope it will help you

¿Le interesa esta conversación? ¡Participe en ella!

Cree una cuenta para poder utilizar funciones exclusivas e interactuar con la comunidad.

Inscribirse
Publicaciones relacionadas Respuestas Vistas Actividad
Odoo 17: How to Create a Custom Table Header in List (Tree) View Using OWL
development
Avatar
0
dic 25
89
How to create custom Table header by using odoo 17
development
Avatar
Avatar
1
dic 25
296
Oddo Integration with Intune
development
Avatar
0
dic 25
1736
@guia@¿Cómo hablar con una persona en Air France?
development
Avatar
0
dic 25
2
How do I change the name of the module, or rather the name assigned to the module, after I created it in Odoo Studio?
development
Avatar
Avatar
1
dic 25
552
Comunidad
  • Tutoriales
  • Documentación
  • Foro
Código abierto
  • Descargar
  • GitHub
  • Runbot
  • Traducciones
Servicios
  • Alojamiento Odoo.sh
  • Ayuda
  • Actualizar
  • Desarrollos personalizados
  • Educación
  • Encontrar un asesor fiscal
  • Encontrar un partner
  • Convertirse en partner
Sobre nosotros
  • Nuestra empresa
  • Activos de marca
  • Contacta con nosotros
  • Puestos de trabajo
  • Eventos
  • Podcast
  • Blog
  • Clientes
  • Información legal • Privacidad
  • Seguridad
الْعَرَبيّة Català 简体中文 繁體中文 (台灣) Čeština Dansk Nederlands English Suomi Français Deutsch हिंदी Bahasa Indonesia Italiano 日本語 한국어 (KR) Lietuvių kalba Język polski Português (BR) română русский язык Slovenský jazyk slovenščina Español (América Latina) Español ภาษาไทย Türkçe українська Tiếng Việt

Odoo es un conjunto de aplicaciones de código abierto que cubren todas las necesidades de tu empresa: CRM, comercio electrónico, contabilidad, inventario, punto de venta, gestión de proyectos, etc.

La propuesta única de valor de Odoo es ser muy fácil de usar y totalmente integrado.

Website made with

Odoo Experience on YouTube

1. Use the live chat to ask your questions.
2. The operator answers within a few minutes.

Live support on Youtube
Watch now