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

How to get a recordset from a One2many or Many2many field in a python file?

Suscribirse

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

Se marcó esta pregunta
v8one2manymany2many
1 Responder
20285 Vistas
Avatar
Alejandro Santana

In v8 I have three models, ModelA, ModelB and ModelC.

  • ModelA has a One2many field: field_b_ids relating ModelA and ModelB.
  • ModelB has a Many2many field: field_c_ids relating ModelB and ModelC.

​Somewhere else I have one id for one ModelA record (a_id).
Doing:

my_a = self.env['model.a'].search([('id', '=', a_id)])

I get the recordset with the one ModelA record I expect. 
From there, I need to get all the ids (or records in a recordset) of ModelC that are in field_c_ids in those ModelB records which are in field_b_ids in my ModelA record.

I thought using mapped() (as read in http://odoo-new-api-guide-line.readthedocs.org/en/latest/environment.html#useful-helpers ) would be my solution, like this:

my_c_ids = my_a.mapped(field_b_ids.field_c_ids)

But mapped() seems to work OK with everything except One2many and Many2many.

Also, trying to go step by step, using loops, if I try to get the ModelB records like this:

my_b_ids = my_a.field_b_ids

This fails complaining about expecting singleton, even if I do:

for a in my_a:

    my_b_ids = a.field_b_ids

I tried variations on this, like using a.field_b_ids[0][2] (seen for XML domains in https://www.odoo.com/forum/help-1/question/how-to-define-a-domain-for-a-field-a-depending-on-the-ids-of-other-field-b-in-a-view-73115 , but it seems to work only in XML domains, not in Python code).

So... How do I get it?

I am running completely out of options here. I feel like it should be easier for o2m, m2m and be (better) documented.

--------

EDIT: [SOLVED]

I already found the problem: I was defining a field as One2many when it should be Many2many (to work with its Many2many counterpart).
Once fixed that, everything works fine and the use of mapped() feels nice and super-easy.

 

 

1
Avatar
Descartar
Avatar
Ivan
Mejor respuesta

my_a is a list of integers (database IDs), you should do self.env['model.a'].browse(my_a) first to get the recordset.  After which you should be able to chain it:

for a in self.env['model.a'].browse(my_a):

    my_b_ids = a.field_b_ids

 

0
Avatar
Descartar
Alejandro Santana
Autor

But in v8 new API search() returns also a recordset, not a list of ids anymore. (See https://www.odoo.com/documentation/8.0/reference/orm.html#common-orm-methods )

Ivan

My apology, you're right. Reading further to the link that you have shared in your question. The example stated that you need to supply a string to mapped. Your code does not seems to supply a string. Maybe that is the problem?

Alejandro Santana
Autor

I found my problem already. A simple stupid one: I defined a field as One2many, when it should be Many2many to be correct. With that fix, mapped works like a charm! (I will edit my question to state this)

¿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
Using the new API.. how do I create a One2many related column? Resuelto
v8 one2many
Avatar
Avatar
Avatar
2
feb 20
18249
Filtering many2many with one2many odoo 8
one2many many2many
Avatar
Avatar
1
sept 15
5736
Reorder one2many_list ? Resuelto
v8 one2many
Avatar
Avatar
2
mar 15
8098
Prevent selecting the same value in one2many field in odoo Resuelto
many2one one2many many2many
Avatar
Avatar
Avatar
Avatar
3
abr 20
11658
Sort widget="many2many_checkboxes" items Resuelto
v8 many2many checkbox
Avatar
Avatar
1
may 19
10832
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