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

Set defaults based on id

Suscribirse

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

Se marcó esta pregunta
defaultsodooV8
3 Respuestas
8694 Vistas
Avatar
tudor

Hello,

I am trying to set some default values, but i can't figure it out. I have added a many2one field to the Product model, which i would like to have the default value of default_code (internal reference) which is a char field. In the _defaults i call the _get_default_code function, where i assume i have to first find the current product and get its default code (i don't know how to do this), then create a new product.code with this value, then return this new product.code. This is what i have so far:

class product_code(osv.osv):
_name = 'product.code'
_columns = {
'name': fields.char('Name', required=True, translate=True),
}

class product_legacy(osv.osv):

_inherit = 'product.template'
_columns = {
'default_code': fields.many2one('product.code', 'Internal Reference'),
}

def _get_default_code(self, cr, uid, context=None):
#get current product's default code
#res = self.pool.get('product.template').search(???)


code_obj = self.pool.get('product.code')
code_obj.create(cr, uid, {
'name': res['name']
}, context=context)

return code_obj

_defaults = {
'default_code':_get_default_code,
}

Even if i put a test value instead of "res['name']" it doesn't do anything. When i create a new product or edit an existing product, the many2one field is still empty.

Thank you for the help.

0
Avatar
Descartar
Prakash

https://www.odoo.com/es_ES/forum/help-1/question/set-default-value-in-object-of-many2one-field-39425

Avatar
tudor
Autor Mejor respuesta

Thank you for the answers. I think i didn't do a very good job explaining my problem. I try again. So, i have the Sales module installed with many products already defined. All the products already have set an 'Internal reference' (default_code). This default_code is of type char.

I have created a module that changes this default_code from char to many2one and references my product.code. This product.code is not defined in the view. I only use it to have this many2one.

The problem is that, as I said, I already have many products with 'internal reference' defined. I would like that when I install my new module, all the 'internal references' already defined to become many2one, with their previous value already set.

So I thought that I can achieve this by setting the _defaults to search for the product with the same id, get the 'internal reference', create a new product.code with it, and set it to the new many2one 'internal reference'.

I don't understand how to search for the product with the same id. Also, even if i return a dummy code_obj from my _get_default_code function, it does not work. The new many2one 'internal reference' is still empty.

Maybe I can't do it like this? Maybe I need to do an update on the database or something.


@Prakash i have already read your post, but i can't figure out how to search for the product with the current id. I assume i have to do something like

self.pool.get('product.product').search(cr, uid, [('id','=',???)], context=context) 

But i don't know what value to search for. Also, as i said, event if I don't use the search and put a dummy code_obj, i get nothing.


@Drees Far I want to have the values set when I install the module, not when I change something. As i said, i think i didn't explain it very well the first time, but maybe now it's more clear.


Thank you

0
Avatar
Descartar
Prakash

Add on_change for product_id field and using browse method get many2one value. if product_id: product_code = product_obj.browse(cr,uid,product_id).product_code.id

Avatar
Rihene
Mejor respuesta

 

Hey friend you can add an on_change function when you click on the code_obj the many2one field will get its containing like this:

Python:

def on_change_state_id(self, cr, uid, ids,code_obj, many_2_one_field, context=None):

if code_obj :
       print code_obj
             res = {'value':{'many_2_one_field':code_obj,
                       }
              }
         return res

else:

My_error_Msg = 'Error : Empty Field'

raise osv.except_osv(_("Error!"), _(My_error_Msg))
   

XML:

<field name="code_obj" on_change="on_change_code_id(code_obj, many_2_one_field)"/>

Regards.


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
[8.0] Is it possible set a default Partner Bank Account when creating a Payment Order
defaults payment_order odooV8
Avatar
0
jun 16
4925
How do you use _defaults in the new API? Resuelto
api defaults odooV8
Avatar
Avatar
Avatar
2
feb 16
7994
CONFIGURACION DE CORREO PROPIO POR PRUMERA VEZ
odooV8
Avatar
0
mar 25
2001
How to remove model if not in the py files anymore
odooV8
Avatar
0
ene 25
4261
Start odoo server automatically in Ubuntu 14.04 on reboot Resuelto
odooV8
Avatar
Avatar
1
ago 23
15885
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