Ir al contenido
Odoo Menú
  • Iniciar sesión
  • Pruébalo gratis
  • Aplicaciones
    Finanzas
    • Contabilidad
    • Facturación
    • Gastos
    • Hoja de cálculo (BI)
    • Documentos
    • Firma electrónica
    Ventas
    • CRM
    • Ventas
    • PdV para tiendas
    • PdV para restaurantes
    • Suscripciones
    • Alquiler
    Sitios web
    • Creador de sitios web
    • Comercio electrónico
    • Blog
    • Foro
    • Chat en vivo
    • eLearning
    Cadena de suministro
    • Inventario
    • Manufactura
    • PLM
    • Compras
    • Mantenimiento
    • Calidad
    Recursos humanos
    • Empleados
    • Reclutamiento
    • Vacaciones
    • Evaluaciones
    • Referencias
    • Flotilla
    Marketing
    • Redes sociales
    • Marketing por correo
    • Marketing por SMS
    • Eventos
    • Automatización de marketing
    • Encuestas
    Servicios
    • Proyectos
    • Registro de horas
    • Servicio externo
    • Soporte al cliente
    • Planeación
    • Citas
    Productividad
    • Conversaciones
    • Aprobaciones
    • IoT
    • VoIP
    • Artículos
    • WhatsApp
    Aplicaciones externas Studio de Odoo Plataforma de Odoo en la nube
  • Industrias
    Venta minorista
    • Librería
    • Tienda de ropa
    • Mueblería
    • Tienda de abarrotes
    • Ferretería
    • Juguetería
    Alimentos y hospitalidad
    • Bar y pub
    • Restaurante
    • Comida rápida
    • Casa de huéspedes
    • Distribuidora de bebidas
    • Hotel
    Bienes inmuebles
    • Agencia inmobiliaria
    • Estudio de arquitectura
    • Construcción
    • Gestión de bienes inmuebles
    • Jardinería
    • Asociación de propietarios
    Consultoría
    • Firma contable
    • Partner de Odoo
    • Agencia de marketing
    • Bufete de abogados
    • Adquisición de talentos
    • Auditorías y certificaciones
    Manufactura
    • Textil
    • Metal
    • Muebles
    • Comida
    • Cervecería
    • Regalos corporativos
    Salud y ejercicio
    • Club deportivo
    • Óptica
    • Gimnasio
    • Especialistas en bienestar
    • Farmacia
    • Peluquería
    Trades
    • Personal de mantenimiento
    • Hardware y soporte de TI
    • Sistemas de energía solar
    • Zapateros y fabricantes de calzado
    • Servicios de limpieza
    • Servicios de calefacción, ventilación y aire acondicionado
    Otros
    • Organización sin fines de lucro
    • Agencia para la protección del medio ambiente
    • Alquiler de anuncios publicitarios
    • Fotografía
    • Alquiler de bicicletas
    • Distribuidor de software
    Descubre todas las industrias
  • Odoo Community
    Aprende
    • Tutoriales
    • Documentación
    • Certificaciones
    • Capacitación
    • Blog
    • Podcast
    Fortalece la educación
    • Programa educativo
    • Scale Up! El juego empresarial
    • Visita Odoo
    Obtén el software
    • Descargar
    • Compara ediciones
    • Versiones
    Colabora
    • GitHub
    • Foro
    • Eventos
    • Traducciones
    • Conviértete en partner
    • Servicios para partners
    • Registra tu firma contable
    Obtén servicios
    • Encuentra un partner
    • Encuentra un contador
    • Contacta a un consultor
    • Servicios de implementación
    • Referencias de clientes
    • Soporte
    • Actualizaciones
    GitHub YouTube Twitter LinkedIn Instagram Facebook Spotify
    +1 (650) 691-3277
    Solicita 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
  • Proyectos
  • 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 10 : Domain and filtering for related fields one2many.

Suscribirse

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

Se marcó esta pregunta
viewsfieldsrelated_fieldsodoo10odoo10.0
2 Respuestas
14708 Vistas
Avatar
Zied Haffoudhi

I have three table :

- product.

- package.

- product_package.


The product_package table have 2 fields which are related to the product and package as it mentionned bellow :

product_id = fields.Many2one('tjara.product', ondelete='cascade', string="Produit", index=True)
package_id = fields.Many2one('tjara.package', ondelete='cascade', string="Emballage", index=True)
_sql_constraints = [
('ligne_unique', 'unique (product_id, package_id)', '%(package_id)d Package is already exists for this product...!')
]


I added the _sql_contraints to avoid the duplicate fields. Because it can be only an unique relation between the product and a package.

And this is what I have in the product model :

product_package_ids = fields.One2many('tjara.product_package', 'product_id', string='Package')

And this is how to add a package from the product view :

                                <page string="Package">
                                    <label for="product_package_ids" string="Emballage"/>
                                    <field name="product_package_ids">
                                        <tree>
                                            <field name="package_id"/>
                                            <field name="price"/>
                                        </tree>
                                        <form>
                                             <field name="package_id"/>
                                            <field name="price"/>
                                        </form>
                                    </field>
                                </page>


This works fine for me. There is only one thing I want to enhance. When the user select an existing package for the product there is no error triggered. The error popped up only when you click "save the product".

I want either to display only the unexisting packages in the select field package_id. Or to pop up an error when the user try to add an existing package for the product.

 

0
Avatar
Descartar
Avatar
Denis Baranov
Mejor respuesta

You can't achieve it by mere xml domain for 'package_id' or 'product_package_ids' since (1) in the latter there is no reference to a product. (2) when you create a product, it doesn't exist yet.

However, you may add the onchange for 'package_id' (in the method of tjara.product_package) to check uniq:


from odoo import exceptions
@api.multi
@api.onchange("package_id")
def onchange_package_id(self):
  for object in self: 
  if object.product_id:
    existing_ids = self.env["tjara.product_package"].search([('product_id','=',object.product_id.id)], limit=1)
    if len(existing_ids) > 0:
      raise exceptions.Warning(_('Package is already exists for this product...!'))
1
Avatar
Descartar
Zied Haffoudhi
Autor

Thanks a lot IT Libertas,

I just replaced the 'object.product_id' by the product's name and I included a search for the package_id also. So I get the following and it's working well :

@api.onchange('package_id')

def onchange_product_package(self):

for object in self:

if object.product_id:

existing_ids = self.env["tjara.product_package"].search([('package_id', '=', object.package_id.id), ('product_id.name', '=', object.product_id.name)], limit=1)

if len(existing_ids) > 0:

raise exceptions.Warning(('Package is already exists for this product...!'))

Avatar
Bejaoui Souheil
Mejor respuesta

Hi,

SQL constraints are checked  when odoo send your request to database. In your case when you click the save button.

Use on_change to display alert message when the user change some values (more details).

@api.onchange('package_id',' product_id')
def onchange_product_package(self):
     if self.search([('package_id',='',self.package_id.id),('product_id_id',='',self.package_id.id)]:
         return {'warning': {'title': _('Warning'), 'message': _('your message.')}}

PS: Odoo have already product class and package classes. I don't think, it is a good idea to create new classes and not inherit the native ones.

Best regards.

1
Avatar
Descartar
Zied Haffoudhi
Autor

Thanks a lot Souheil :)

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

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

Registrarse
Publicaciones relacionadas Respuestas Vistas Actividad
Is there an option or method to auto select the value in a field when you click on it in edit mode?
views fields odoo10
Avatar
Avatar
1
mar 19
5151
Odoo 10 - Inherited template field appears depends upon position Resuelto
views fields inherit odoo10
Avatar
Avatar
2
mar 18
5419
[CLOSED] I'm getting a validation error "Some fields are not set" set when using dynamic attributes. Resuelto
attrs views fields form_view odoo10
Avatar
Avatar
Avatar
8
dic 22
6541
Odoo 10 : Related fields and inheritance from third parent. (one2many)
fields relationship related related_fields odoo10
Avatar
0
may 17
3619
Related field; Error: 'Environment' object has no attribute 'picking_state'
related_fields odoo10
Avatar
0
abr 20
5670
Comunidad
  • Tutoriales
  • Documentación
  • Foro
Código abierto
  • Descargar
  • GitHub
  • Runbot
  • Traducciones
Servicios
  • Alojamiento en Odoo.sh
  • Soporte
  • Actualizaciones del software
  • Desarrollos personalizados
  • Educación
  • Encuentra un contador
  • Encuentra un partner
  • Conviértete en partner
Sobre nosotros
  • Nuestra empresa
  • Activos de marca
  • Contáctanos
  • Empleos
  • Eventos
  • Podcast
  • Blog
  • Clientes
  • 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 estar 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