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

Fields.function with type one2many in wizard

Suscribirse

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

Se marcó esta pregunta
wizardone2manymany2manyfields.function
3 Respuestas
14805 Vistas
Avatar
Cyril Sester

Hi,

I have data with a many2many relation between 2 models. Simplified model is :

Class property(orm.Model):

        _name = 'property'

        _columns = {

                'value_ids': fields.many2many(

                        'value', 'property_value', 'property_id', 'value_id', _('Values'))

        }

Class value(orm.Model):

        _name = 'value'

        _columns = {

                'property_ids': fields.many2many(

                        'property', 'property_value', 'value_id', 'property_id', _('Properties')),

                'field1': fields.char(_('Field 1')),

                'field2': fields.char(_('Field 2'))

        }

class dummy(orm.Model):

       _name = 'dummy'

       _columns = {

            'case_study_ids': fields.one2many(
                  'property', 'dummy_id', string=_('Properties'))

      }

Until here, everything works fine. Now, on my dummy model form view I have a button who launch a wizard who makes some process over values for a specific property (id passed in context). This wizard first shows values associated to property and allows modifications on them. Then, the internal process is done.

class property_process_wizard(orm.TransientModel):
        _name = 'property.process.wizard'
    
        def get_value_ids(self, cr, uid, ids, field_name, arg, context=None):
                property_id = context.get('property_id', False)
                if not property_id:
                        return dict([(id, []) for id in ids])

                value_obj = self.pool.get('value')
                value_ids = value_obj.search(cr, uid, vals = [('property_id', '=', property_id)])
                return dict([(id, value_ids) for id in ids])

 

        _columns = {

                'value_ids': fields.function(get_value_ids, type='one2many',
                                                                                                   obj='value'),

        }

Here is my problem. The field function is not computed when the wizard is launched. Is there a way to force field computation on wizard launching?

Best regards,

 

0
Avatar
Descartar
Avatar
Cyril Sester
Autor Mejor respuesta

One more time, I will give myself the answer.

It's sadly simple, as it's done with the _defaults. For example : 

...

def get_value_ids(self, cr, uid, ids, field_name, arg, context=None):
        property_id = context.get('property_id', False)
        if not property_id:
                return dict([(id, []) for id in ids])

        value_obj = self.pool.get('value')
        value_ids = value_obj.search(cr, uid, vals = [('property_id', '=', property_id)])
        return dict([(id, value_ids) for id in ids])

 

       _columns = {       

                'value_ids': fields.function(get_value_ids, type='one2many',
                                                                                                   relation='value'),

        }

        _defaults = {

                'value_ids': lambda self, cr, uid, context : self.get_value_ids(cr, uid, [0], '', '', context)[0],

        }

The trick is to use a lambda function and pass a fake ids list to match de function implementation.

0
Avatar
Descartar
Avatar
Ivan
Mejor respuesta

get_value_ids method should handle multiple ids.  So it should be something like:

def get_value_ids(self, cr, uid, ids, field_name, arg, context=None):
                property_id = context.get('property_id', False)
                value_ids = []

                if property_id:
                        value_obj = self.pool.get('value')
                        value_ids = value_obj.search(cr, uid, vals = [('property_id', '=', property_id)]
                return dict([(x, value_ids) for x in ids])

0
Avatar
Descartar
Cyril Sester
Autor

Yep, you're totally right. One more time, I was too fixed on my use case ! I just improved my code to handle multiple ids (even if it should never happen).

Avatar
Emipro Technologies Pvt. Ltd.
Mejor respuesta

Hi,

You have to just change the defination of your fields as like below.

Class property(orm.Model):

        _name = 'property'

        _columns = {

                'value_ids': fields.many2many(

                        'value', 'property_value', 'property_id', 'value_id', _('Values'))

        }

Class value(orm.Model):

        _name = 'value'

        _columns = {

                'property_ids': fields.many2many(

                        'property', 'property_value', 'value_id',  'property_id',_('Properties')),

You have to just redefine the column of the 'value' model. In that you have to specify the first column for the 'value' model and second column for the 'property' model. 

I think this is the first thing you have to correct.

-1
Avatar
Descartar
Cyril Sester
Autor

Just a small mistake who went in when writing the simplified relationship. Was right in the code. Everything works fine, from properties I see associated values and from values associated properties. My problem is only in the wizard where the fields.function isn't computed on wizard creation.

¿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
How to open wizard from "Add a line" link of One2many field?
wizard one2many
Avatar
Avatar
1
jun 24
443
How to transfer id created wizard into main form?
wizard many2many
Avatar
Avatar
1
jul 18
4044
One2many through wizard, (without errors, but no add to the record)
wizard one2many
Avatar
Avatar
1
feb 16
5897
Many2many field in wizard is showing empty (v9) ?
wizard many2many
Avatar
0
ene 16
4196
Filtering many2many with one2many odoo 8
one2many many2many
Avatar
Avatar
1
sept 15
5880
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