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
    • eLearning
    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
    • Información
    • 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 taberna
    • 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
    • Brewery
    • Regalos de empresas
    Salud y bienestar
    • Club deportivo
    • Óptica
    • Gimnasio
    • Terapeutas
    • Farmacia
    • Peluquería
    Oficios
    • Handyman
    • Hardware y asistencia informática
    • 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
    Browse all Industries
  • 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
    • Services for 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

[odoo 8 ] : How to update value of one2many field with at second level by using create and write method using API?

Suscribirse

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

Se marcó esta pregunta
one2manycreateupdatewriteodooV8
6 Respuestas
64821 Vistas
Avatar
Prince Caspion

Hello All,

I've asked this Question again, because i was not able to EDIT my question.

I'm having problem on overriding create method.

I've one2many field in my current model, I want to update the value of that field when new record created, and this one2many field's co-model has it's own one2many fields.

So, basically there is two levels of one2many fields.

My one2many field has one2many field, I want to create record for that model as well,

How can i achieve this?

Any help on this appreciated.

This is need to be done using api coding standard.

EDIT

E.g.

Class A(models.Model):    
_name = 'main.model'
x_ids = fields.one2Many('sub.model','main_id',"Test")

   

Class B(models.Model)    
_name = 'sub.model'   
main_id = fields.Many2one('main.model', "Main Model")
#remaining fields.
xx_ids = fields.One2many('another.sub.model','sub_model_id',"Test")
Class C(models.Model)    
_name = 'another.submodel'
sub_model_id = fields.Many2one('sub.model',"Sub Model")
#remaining fields..go here   

Consider this is model structure, now when i create record of Class A model, I want to updated one2many field of Class B and Class B is having Class C one2many field, so how to update the values or create records with 2 level of one2many field? is there any option?

I am looking for the solution for both side create and write method. Please anyone has idea than it will be really helpful.

Regards,

Prince

2
Avatar
Descartar
Avatar
Deepa Venkatesh
Mejor respuesta

You can achieve that in 2 ways:

Case 1: Default Values

if you have fixed data, then you can set default values in both objects i.e in ClassA set default values for 'x_ids' and in ClassB set default values for 'xx_ids'

Case 2: Create/Write method

In the First object (ClassA): while creating itself you can add its lines using One2Many and/or Many2Many semantics.


According to your sample object hierarchy:


@api.model

def create(self, vals):

valsC = {....} # dict of values needed for creating ClassC

valsB = {
'xx_ids': [(0, 0, valsC)],

          ....} # dict of values needed for creating ClassB

vals['x_ids'] = [(0, 0, valsB)] # appending it into the values of ClassA

return super(A, self).create(vals)



In Odoo, at the time of creating a record, you can pass values to its child be it a One2Many or Many2Many by using its semantics, here [(0,0,{})] represents am trying to create new One2Many record.

Note:

In valsB, I have appended the values of ClassC, and this dict am appending the original Vals of Class A, which will be like passing nested dict of values into ClassA

Similarly there exists a semantics for editing/updating, deleting and so, please refer the below samples which are used for both One2Many & Many2Many.


(0, 0, { values }) link to a new record that needs to be created with the given values dictionary

(1, ID, { values }) update the linked record with id = ID (write values on it)

(2, ID) remove and delete the linked record with id = ID (calls unlink on ID, that will delete the object completely, and the link to it as well)

(3, ID) cut the link to the linked record with id = ID (delete the relationship between the two objects but does not delete the target object itself)

(4, ID) link to existing record with id = ID (adds a relationship)

(5) unlink all (like using (3,ID) for all linked records)

(6, 0, [IDs]) replace the list of linked IDs (like using (5) then (4,ID) for each ID in the list of IDs)

7
Avatar
Descartar
Avatar
Kirubanidhi Rajarathinam
Mejor respuesta

Update  A SAMPLE one2many record in odoo9, 

search_var = self.browse(self.id)

search_var.update({

'stud_ids': [(0,_, {

'reg_no':4200,

'dob': '04/01/1992',

'stud_name':'amuthan',

})]

})

1
Avatar
Descartar
Avatar
Qutechs, Ahmed M.Elmubarak
Mejor respuesta

Hello,

In creation you need to override the create method of class A to be something as:

@api.model

def create(self, vals):

res = super(A, self).create(vals)

#creating C record

c_res = self.env['another.submodel'].create({'field_name': value, ...})

#creating B record

b_res = self.env['sub.model'].create({'field_name': value, ...})

#Adding C to B

b_res.xx_ids += c_res

#Adding B to A [it is also a One2many]

res.x_ids += b_res

return res

You can do similar thing in the write method with some modifications ...


Hope this could helps ...

0
Avatar
Descartar
Prince Caspion
Autor

@Ahmed: Thanks for the nice example, i will try and check it.

Prince Caspion
Autor

Ahmed given solution does not work , gives me this error, defaults.update(values)

ValueError: dictionary update sequence element #0 has length 3; 2 is required

Qutechs, Ahmed M.Elmubarak

Hi, can you share your code some where ?

¿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
Best way to create one2many records in backend
one2many create update
Avatar
0
nov 22
4973
how to override create or write method Resuelto
one2many create write
Avatar
Avatar
Avatar
3
jul 17
12685
update one2many field
function one2many create update
Avatar
0
abr 19
4304
[odoo 8]: How set value of one2many field by overriding create method with api coding standard? Resuelto
one2many create api override odooV8
Avatar
Avatar
2
dic 20
9202
how to update odoo One2many field from list of dictionaries?
one2many create update loop dictionary
Avatar
Avatar
3
jul 20
18782
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