Ir al contenido
Odoo Menú
  • Iniciar sesión
  • Pruébalo gratis
  • Aplicaciones
    Finanzas
    • Contabilidad
    • Facturación
    • Gastos
    • Hoja de cálculo (BI)
    • Documentos
    • Firma electrónica
    Ventas
    • CRM
    • Ventas
    • PdV para tiendas
    • PdV para restaurantes
    • Suscripciones
    • Alquiler
    Sitios web
    • Creador de sitios web
    • Comercio electrónico
    • Blog
    • Foro
    • Chat en vivo
    • eLearning
    Cadena de suministro
    • Inventario
    • Manufactura
    • PLM
    • Compras
    • Mantenimiento
    • Calidad
    Recursos humanos
    • Empleados
    • Reclutamiento
    • Vacaciones
    • Evaluaciones
    • Referencias
    • Flotilla
    Marketing
    • Redes sociales
    • Marketing por correo
    • Marketing por SMS
    • Eventos
    • Automatización de marketing
    • Encuestas
    Servicios
    • Proyectos
    • Registro de horas
    • Servicio externo
    • Soporte al cliente
    • Planeación
    • Citas
    Productividad
    • Conversaciones
    • Aprobaciones
    • IoT
    • VoIP
    • Artículos
    • WhatsApp
    Aplicaciones externas Studio de Odoo Plataforma de Odoo en la nube
  • Industrias
    Venta minorista
    • Librería
    • Tienda de ropa
    • Mueblería
    • Tienda de abarrotes
    • Ferretería
    • Juguetería
    Alimentos y hospitalidad
    • Bar y pub
    • Restaurante
    • Comida rápida
    • Casa de huéspedes
    • Distribuidora de bebidas
    • Hotel
    Bienes inmuebles
    • Agencia inmobiliaria
    • Estudio de arquitectura
    • Construcción
    • Gestión de bienes inmuebles
    • Jardinería
    • Asociación de propietarios
    Consultoría
    • Firma contable
    • Partner de Odoo
    • Agencia de marketing
    • Bufete de abogados
    • Adquisición de talentos
    • Auditorías y certificaciones
    Manufactura
    • Textil
    • Metal
    • Muebles
    • Comida
    • Cervecería
    • Regalos corporativos
    Salud y ejercicio
    • Club deportivo
    • Óptica
    • Gimnasio
    • Especialistas en bienestar
    • Farmacia
    • Peluquería
    Trades
    • Personal de mantenimiento
    • Hardware y soporte de TI
    • Sistemas de energía solar
    • Zapateros y fabricantes de calzado
    • Servicios de limpieza
    • Servicios de calefacción, ventilación y aire acondicionado
    Otros
    • Organización sin fines de lucro
    • Agencia para la protección del medio ambiente
    • Alquiler de anuncios publicitarios
    • Fotografía
    • Alquiler de bicicletas
    • Distribuidor de software
    Descubre todas las industrias
  • Odoo Community
    Aprende
    • Tutoriales
    • Documentación
    • Certificaciones
    • Capacitación
    • Blog
    • Podcast
    Fortalece la educación
    • Programa educativo
    • Scale Up! El juego empresarial
    • Visita Odoo
    Obtén el software
    • Descargar
    • Compara ediciones
    • Versiones
    Colabora
    • GitHub
    • Foro
    • Eventos
    • Traducciones
    • Conviértete en partner
    • Servicios para partners
    • Registra tu firma contable
    Obtén servicios
    • Encuentra un partner
    • Encuentra un contador
    • Contacta a un consultor
    • Servicios de implementación
    • Referencias de clientes
    • Soporte
    • Actualizaciones
    GitHub YouTube Twitter LinkedIn Instagram Facebook Spotify
    +1 (650) 691-3277
    Solicita 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
  • Proyectos
  • 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

function to get last or greatest value

Suscribirse

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

Se marcó esta pregunta
python3odoo16features
2 Respuestas
3381 Vistas
Avatar
SmithJohn45

i am requesting to please help to get last element + 1 or greatest value for:

the field values are as follow:

1) field name: x_field1   value: ABC    -- can have more values

2) field name: x_field2  value: XYZ    -- can have more values

Model is approval.request.

the value in a field to store: ABC-XYZ-00090 (this value stored in 'name' field)

i want to add an Automated Rule or Automation Rule to get 00091 (last or greatest + 1) and concatenate as current x_field1-x_field2-00091, if there is no record exist for combination of x_field1-x_field2 then it will return 1...  i know this is very basic for python experts but not for me.

i tried to search on net but still confused as per my knowledge level. please help to write python function.

note: during my search for it, i found code below but don't know how to implement for my requirement:

partner_ids = env['res.partner'].search([], order="create_date desc", limit=1)

last_partner = partner_model.browse(partner_ids)

regards


0
Avatar
Descartar
Avatar
Tim Schmidt
Mejor respuesta

Hi, try asking ChatGPT. It answered me this, maybe it helps:


You want to automate the creation of a sequence number for an approval.request record. The main goal is to get the last sequence number used and increment it by one.

Here is a refined version of your code. This should work within an Automation Rule in Odoo. The code will search for the last sequence, increment it, and then set it for the new record.

if record.request_status == 'new':
    # Search for the last record with similar x_field1-x_field2 combination
    last_record = record.env['approval.request'].search(
        [('name', 'ilike', record.x_field1 + '-' + record.x_field2 + '-%')],
        order="name desc",
        limit=1
    )

    if last_record:
        # Extract the number part from the last record's name
        last_number_str = last_record.name.split('-')[-1]
        last_number = int(last_number_str)
        next_number = str(last_number + 1).zfill(5)
    else:
        next_number = '00001'

    # Create the new sequence name
    seq = f"{record.x_field1}-{record.x_field2}-{next_number}"
    record.write({'name': seq})

Explanation:

  1. Condition Check: The code first checks if the `request_status` of the record is 'new'.
  2. Search for Last Record: It searches for the last record with a similar `x_field1-x_field2` combination using the `ilike` operator to perform a case-insensitive search. The search is ordered by the `name` field in descending order to get the latest one.
  3. Extract and Increment: If a last record is found, it extracts the numerical part from the `name`, converts it to an integer, increments it by one, and then pads it with leading zeros to maintain the format.
  4. Create New Sequence: If no last record is found, it starts with '00001'. The new sequence is then formatted and written back to the record.

This code assumes that the `name` field always follows the pattern `x_field1-x_field2-00090`. Adjust the padding length (`zfill(5)`) according to the required format.

Shorter:

if record.request_status == 'new':
    last_record = record.env['approval.request'].search(
        [('name', 'ilike', record.x_field1 + '-' + record.x_field2 + '-%')],
        order="name desc", limit=1
    )
    next_number = str(int(last_record.name.split('-')[-1]) + 1).zfill(5) if last_record else '00001'
    record.write({'name': f"{record.x_field1}-{record.x_field2}-{next_number}"})

This version does the same thing but in fewer lines:

  1. Condition Check: Checks if the request_status is 'new'.
  2. Search for Last Record: Searches for the last record with the matching pattern.
  3. Extract, Increment, and Format: If a last record is found, it extracts, increments, and formats the number. If not, it defaults to '00001'.
  4. Write New Sequence: Writes the new sequence back to the name field.


Make sure to test this thoroughly in a development environment before deploying it in production. 

0
Avatar
Descartar
Avatar
SmithJohn45
Autor Mejor respuesta

i tried this code in Automation Rule:


Name: Testing

Model: Approval Request


Execute Code:

if record.request_status=='new':

  print(record.request_status)

  last_name = record.env['approval.request'].search([('name', 'ilike', record.x_field1+'-'+record.x_field2), order="to_number('name') desc", limit=1)[-1].name + 1

  print(last_name)

  if last_name:

     seq = record.x_field1+'-'+x_field2+'-'+last_name

  else:

      seq = record.x_field1+'-'+x_field2+'-'+'0001'


  record.write({'name': seq})


but its not working, even not showing the print() function output.

please help.

regards


0
Avatar
Descartar
SmithJohn45
Autor

nobody can help yet?

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

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

Registrarse
Publicaciones relacionadas Respuestas Vistas Actividad
Cannot upgrade to enterprise edition
enterprise python3 odoo16features
Avatar
Avatar
2
abr 23
3530
Fail to register a payment for a Bill
python3 odoo odoo16features
Avatar
Avatar
1
mar 23
2851
DeprecationWarning: The longpolling-port is a deprecated alias to the gevent-port option, please use the latter Resuelto
odoo16features
Avatar
Avatar
Avatar
Avatar
Avatar
5
sept 25
24366
How to Add wizard under print button inside the form view.
odoo16features
Avatar
Avatar
Avatar
Avatar
3
ago 25
3725
How to add @api.onchange in _get_view() method odoo 16
odoo16features
Avatar
Avatar
1
may 25
3610
Comunidad
  • Tutoriales
  • Documentación
  • Foro
Código abierto
  • Descargar
  • GitHub
  • Runbot
  • Traducciones
Servicios
  • Alojamiento en Odoo.sh
  • Soporte
  • Actualizaciones del software
  • Desarrollos personalizados
  • Educación
  • Encuentra un contador
  • Encuentra un partner
  • Conviértete en partner
Sobre nosotros
  • Nuestra empresa
  • Activos de marca
  • Contáctanos
  • Empleos
  • Eventos
  • Podcast
  • Blog
  • Clientes
  • 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 estar 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