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

Hierarchy relationship

Suscribirse

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

Se marcó esta pregunta
v14
5215 Vistas
Avatar
Răzvan Anastasescu

I have extended Sale Order Line with parent / child hierarchy relationship because some lines (children) can be connected to others (parent) in the same Sale Order

class SaleOrderLine(models.Model):
_inherit = 'sale.order.line'
  _parent_name = 'my_parent_id'

my_parent_id = fields.Many2one('sale.order.line', 'Operation for', index=True, domain='[("my_parent_id", "=", False)]', ondelete='cascade')

my_children_ids = fields.One2many('sale.order.line', 'my_parent_id', 'Operations')

I am presenting children records differently in the view (different row color, disabled re-sequennce, and so on) based on the `my_parent_id` field (and I am also dealing with re-sequencing of the children together with the parent and all the rest) which is working fine

The problem I have is that I don't know how to properly add a new parent line with couple of children records on changing some field of an existing line (in the same Sale Order)

Meaning that if I change the quantity of one line, based on some conditions of course, I need to add another parent line with couple of children lines.

There are actually two problems, combined (examples of code below):

  1. Where exactly to put the code ?

    1. Most logical place would be in `sale_order_line.onchange('product_uom_qty')`
      But here I couldn't add even the single parent line using `self.new()` (it's just not showing up) although I'm on the same model, and using `self.create()` it's working but the new records do not show up until the user saves the Sale Order or just refresh / reloads it (as the records have been created into the DB using create() method)

    2. I did try also on `sale_order.onchange('order_line')`
      Here it's working to add the lines even with `new()` but the problem is that the parent / child relationship it's not held

  2. What method to use ?

    1. `sale_order_line.new()` - I would have preferred not to have the records saved into DB directly (in order to allow user to discard the change) but at least one method to work would be nice ... but this is not keeping the parent / child relationship
      Although if using debugger on the moment they're added, the connection between them seems fine using the NewIDs but as soon as the transaction finishes (I don't know which other code it's executing after my function) the relation drops (on next debug the relationship fields are empty)

    2. `sale_order_line.create()` - this seems to work, adding first the parent line and then connecting each child with the parent record ID, but the records do not show up in the view until user saves the Sale Order or simply refreshes / reloads the page

    3. `sale_order.update({'order_line': [(0, 0, {'product_id': parent, 'my_children_ids': [(0, 0, child products ...)]})` same issues as above


Code examples:

1. using `sale_order_line.new()` inside `sale_order_line._onchange_product_uom_qty()` method

not working at all, even for the single parent line, it doesn't show up ...

# in my SaleOrderLine extension class
@api.onchange('product_uom_qty')
def _onchange_product_uom_qty(self):
new_parent_line = self.new({
'order_id': rec.order_id.id,
'product_id': 10,
# I'm adding all the other required fields just to be sure ...
'name': 'Test parent',
'price_unit': 10,
'product_uom_qty': 1,
})


2. using `sale_order_line.create()` inside `sale_order_line._onchange_product_uom_qty()` method

it's working, even adding child lines correctly, but:

  •  they are not visible to the user until Sale Order get's saved manually by the user (which does some kind of refresh afterwards) or entire page reloaded (as the records are already saved in the DB)
    Is there a method to save the Sale Order from code and automatically show the new records created ?

  • it would have been nice to be able to use the discard functionality (like new()) - but anyway, at least one decent way to achieve what I need would be nice though (correct parent / child relationship and displayed to the user after the change ...)

# in my SaleOrderLine extension class
@api.onchange('product_uom_qty')
def _onchange_product_uom_qty(self):
new_parent_line = self.create({
# I need to use the _origin to take order integer ID instead of the NewID format in order to work correctly ...
'order_id': rec._origin.order_id.id,
'product_id': 10,
# I'm adding all the other required fields just to be sure ...
'name': 'Test parent',
'price_unit': 10,
'product_uom_qty': 1,
# this doesn't work to automatically create children records too ...
# 'my_children_ids': [
# (0, 0, {child 1 values ...}),
# (0, 0, {child 2 values ...}),
# ],
})

new_child_1_line = self.create({
'my_parent_id': new_parent_line.id,
# other child 1 values ...
})


3. using `sale_order.order_line.new()` from `sale_order._onchange_order_line()`

The records show up, but the parent / child relation it's not kept

Actually debugging the code during execution which adds them, the relationship seems fine (based on the NewIDs), but as soon as the code ends (and whatever the framework does afterwards) it seems that is broken

I've debugged again and for those records the link fields (parent / child) are empty

 

# in my SaleOrder extension class
@api.onchange('order_line')
def _onchange_order_line(self):
new_parent_line = self.order_line.new({
'order_id': self.id,
'product_id': 10,
# I'm adding all the other required fields just to be sure ...
'name': 'Test parent',
'price_unit': 10,
'product_uom_qty': 1,
   'my_children_ids': [
(0, 0, {child 1 values ...}),
(0, 0, {child 2 values ...}),
]
})


4. using `sale_order.update({'order_line': [(0, 0, {parent values ...}]})` from `sale_order._omchange_order_line()`

the same like point above, they appear but without parent / child relation

# in my SaleOrder extension class
@api.onchange('order_line')
def _onchange_order_line(self):
self.update({
'order_line': [(0, 0, {
'order_id': self.id,
'product_id': 10,
# I'm adding all the other required fields just to be sure ...
'name': 'Test parent',
'price_unit': 10,
'product_uom_qty': 1,
    'my_children_ids': [
(0, 0, {child 1 values ...}),
(0, 0, {child 2 values ...}),
]
})]
})


Are there any other ways to achieve what I need ?

Thx,

0
Avatar
Descartar
¿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
Attached PDF file is not formatted properly
v14
Avatar
Avatar
1
dic 25
404
Odoo14 alternative for Automated Translations through Gengo API module
v14
Avatar
Avatar
Avatar
Avatar
3
sept 25
3830
Odoo Community v14 Slow on High-End Servers, Fast on i5/i7 PCs
v14
Avatar
0
ago 25
1223
How to Managing Birthdate and Age in Odoo
v14
Avatar
Avatar
1
ago 25
3629
Update Initial Stock of Product using XMLRPC API [Odoo14] Resuelto
v14
Avatar
Avatar
Avatar
2
jul 25
9255
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 empresariales de código abierto que cubre 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