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

complex many2many domains in views

Suscribirse

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

Se marcó esta pregunta
1 Responder
32964 Vistas
Avatar
YannickB

Hello everyone,

I have some complex many2many domain to do and I am not able to make it works. Let me described the case :

I created two many2many fields in res.partner, skill_category_ids and skill_tags_ids

They point to two object marketplace.category and marketplace.tag. The object marketplace.category has only the name field. The object marketplace.tag has the name field and a required many2one field which point to marketplace.category.

In res.partner form, I want to be able to only select the tags which belong to category we selected in skill_category_ids. Here is my try :

<field name="skill_category_ids"/>
<field name="skill_tag_ids" domain="[('category_id','in',skill_category_ids)]"/>

It give the following traceback when I try to open the skill_tags_ids field :

  Server Traceback (most recent call last):
  File "/opt/openerp/openerp-wezer-dev/web/addons/web/session.py", line 89, in send
    return openerp.netsvc.dispatch_rpc(service_name, method, args)
  File "/opt/openerp/openerp-wezer-dev/server/openerp/netsvc.py", line 292, in dispatch_rpc
    result = ExportService.getService(service_name).dispatch(method, params)
  File "/opt/openerp/openerp-wezer-dev/server/openerp/service/web_services.py", line 626, in dispatch
    res = fn(db, uid, *params)
  File "/opt/openerp/openerp-wezer-dev/server/openerp/osv/osv.py", line 188, in execute_kw
    return self.execute(db, uid, obj, method, *args, **kw or {})
  File "/opt/openerp/openerp-wezer-dev/server/openerp/osv/osv.py", line 131, in wrapper
    return f(self, dbname, *args, **kwargs)
  File "/opt/openerp/openerp-wezer-dev/server/openerp/osv/osv.py", line 197, in execute
    res = self.execute_cr(cr, uid, obj, method, *args, **kw)
  File "/opt/openerp/openerp-wezer-dev/server/openerp/osv/osv.py", line 185, in execute_cr
    return getattr(object, method)(cr, uid, *args, **kw)
  File "/opt/openerp/openerp-wezer-dev/server/openerp/osv/orm.py", line 2369, in search
    return self._search(cr, user, args, offset=offset, limit=limit, order=order, context=context, count=count)
  File "/opt/openerp/openerp-wezer-dev/server/openerp/osv/orm.py", line 4887, in _search
    cr.execute('SELECT "%s".id FROM ' % self._table + from_clause + where_str + order_by + limit_str + offset_str, where_clause_params)
  File "/opt/openerp/openerp-wezer-dev/server/openerp/sql_db.py", line 161, in wrapper
    return f(self, *args, **kwargs)
  File "/opt/openerp/openerp-wezer-dev/server/openerp/sql_db.py", line 226, in execute
    res = self._obj.execute(query, params)
TypeError: not all arguments converted during string formatting

And this is not all, I also created an object marketplace.announcement which have a many2one to marketplace.category and a many2many to marketplace.tags. I want to create a filter which will only display announcement which have their category in the skill_category_ids of the user or have at least one tag in the skill_tags_ids of the user.

Here is my try :

<filter name="my_skills" string="My skills" domain="['|',('category_id','in',uid.partner_id.skill_category_ids),('tag_ids','in',uid.partner_id.skill_tag_ids)]" icon="terp-check"/>

I have the following error message when I load the filter :

TypeError: results.group_by is undefined

This is really a complex case, with domain between two many2many fields, I don't think I'll be able to figure out by myself how I'll achieve that, and I didn't found a workaround until now. I hope you guys will have some ideas.

Thanks you, Yannick.

9
Avatar
Descartar
Sehrish

You can get an idea: https://learnopenerp.blogspot.com/2021/03/domain-filter-one2many-child-fields-on-the-basis-of-parent-fields.html

Avatar
Olivier Dony (odo)
Mejor respuesta

For the first part of the question, you have to know that the web client outputs the value of local "many2many" using the writeable syntax. So if you have 3 entries in a m2m it will return them in this format: [(6,0,[ID1,ID2,ID3])]. This means that the domain [('category_id','in',skill_category_ids)] will actually render as: [('category_id','in',[(6,0,[ID1,ID2,ID3])])] which is invalid and will give the kind of error you are seeing. You can easily see it if you look at the actual RPC being triggered in your web browser (network debug).

A quick and dirty fix for this is to change your domain expression to extract the list of IDs from the value returned by the client: [('category_id','in',skill_category_ids and skill_category_ids[0][2])]. Another way would be to set an on_change trigger on the skill_category_ids field and set the domain for the relevant fields in the result of the on_change.


For the second part, your filter domain is invalid because it has to be evaluated on the client-side only (it's dynamically applied when you use the search view). In this context the uid value is just a pure integer, not a browse_record (this concepts exists only on the server-side). You have to write the domain in a different way that only requires uid on the right side, for example (relationship names may be wrong, I only guessed them):

<filter name="my_skills" string="My skills" domain="['|',('category_id.tag_ids.partner_ids.user_ids','in',uid),('tag_ids.partner_ids.user_ids','in',uid)]" icon="terp-check"/>
17
Avatar
Descartar
René Schuster

One of the best answers on help.oerp!

Thanks a lot!

The only thing that confuses me, is that the 'in' operator in domains seems to be 'reversible'... ([list], in, int) oO

Olivier Dony (odo)

@René: yes this may be surprising at first, the meaning of the in operator is reversed when used for a one2many or many2many field. It is basically a contains operator in that case, but OpenERP does not have this operator. It may be easier to understand if you think of it as a comparison that is attempted for each existing line of the relationship. For example [('x2m_ids', '=', 12)] is valid and will match any record that has line 12 in its x2m_ids, regardless of the other lines. Domains onx2many fields are often non-trivial because of this (especially negative expressions!)

René Schuster

wow. thx. i've been looking for this explanation for a very long time now.

YannickB
Autor

As competent as ever Olivier, really thanks a lot this is a really good answer. Now it works perfectly, mainly I didn't though that many2many was also a 6,0,[ids] in view, and for second part I needed to create the one2many tag_ids and partner_ids to use your code, which is now done. Thanks again :).

Aron Lorincz

I can report that [0][2] works in Odoo 9. Saying it because I thought it doesn't: tried about 100 times, then it started working.

Cezar Jr

I have a problem, my field is m2m and I like to filter if it has more them one rows, like this domain="[[u'tag_ids', u'&gt', 1]], but did not work and I don't have any ideia of how to make a function to count the number of rows, could you give some help?

jianxin

In Odoo 10, seems that m2m values are rendered as "[ID1,ID2,ID3]" in the view, not "[(6,0,[ID1,ID2,ID3])]" ...

jianxin

Not correct for the above comment, STILL "[(6,0,[ID1,ID2,ID3])]" in Odoo 10. I don't have enough karma to delete it. Sorry for that.

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

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

Inscribirse
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