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

How to prevent from adding same products in sale order line

Suscribirse

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

Se marcó esta pregunta
odooodoo12Odoo13.0
1 Responder
6814 Vistas
Avatar
Madara

hi all iam a newbie to odoo , what iam trying to achieve is i want to prevent from adding duplicate products in order line , if the same exits already we should not able to add the duplicate product 


    @ api.multi

    @ api.constrains ('order_line')

    def _check_exist_product_in_line (self):

      for rec in self:

          product_id = self.env ['product.product']. search ([('default_code', '=', 'MIFFLIN')])

          for line in self.order_line:

             if line.product_id.id in product_id:

                raise ValidationError (_ ('Product already added.'))

             product_id.append (line.product_id.id)



i tried like this but it's not working its throwing operation not permitted. what am i missing here , someone help me here

0
Avatar
Descartar
Madara
Autor

TypeError: Mixing apples and oranges: product.product(28,) in sale.order.line(572,)

Avatar
Mohamed Lamine Lalmi
Mejor respuesta

Hello Mascherano,

Comparing what you want to achieve with what your code does seem like two different things to me.

I feel your code will solve your situation, you can just fix it like the following:

  1. Please do not use @api.multi & @api.constrains on the same function

  2. the result of self.env ['product.product']. search ([('default_code', '=', 'MIFFLIN')]) is product.product object set and not an integer and you are trying to compare this set of objects with an integer on if line.product_id.id in product_id (line.product_id.id is an integer value) ==> This throws the error: TypeError: Mixing apples and oranges

  3. Bellow is the fix of your code:

@api.constrains ('order_line')
def _check_exist_product_in_line(self):
product_ids = self.env['product.product'].search([('default_code', '=', 'MIFFLIN')])
for rec in self:
for line in rec.order_line:
if line.product_id in product_ids:
raise ValidationError(_('Product already added.'))
product_id.append(line.product_id.id)
    return True

Let me explain a little bit what's your code is for:

  1. Get all the products that has 'MIFFLIN' as a default code.

  2. You loop on the Sale order lines

  3. If the line's product is one of the products searched on step 1 then raise an error.

  4. So your code will always raise an error if 'MIFFLIN' product is present on sale order lines even that is not duplicated (exist only once).

Honestly, i don't believe your code will help you to achieve your explained goal, If you feel the same, please to use the bellow code:

@api.constrains ('order_line')
def _check_exist_product_in_line(self):
for order in self:
products_in_lines = order.mapped('order_line.product_id')
for product in products_in_lines:
lines_count = len(order.order_line.filtered(lambda line: line.product_id == product))
if lines_count > 1:
raise ValidationError(_('Product already added.'))
return True

Hope this will help,

Good luck.

0
Avatar
Descartar
Madara
Autor

when i try to add the product , it showing as error product_id is not defined

Zartash Baig

product_ids = []
for line in self.order_line:
product_ids.append (line.product_id.id)
occurrences = product_ids.count (self.product_id.id)
if occurrences> 2:
raise ValidationError ('You cannot select already added product.' )

Zartash Baig

Onchange product_id

¿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
Can I use select ="multi" with selection field in search panel tag in sale order tree view?
odoo odoo12 Odoo13.0
Avatar
Avatar
1
jun 23
5568
Odoo Installation Script Resuelto
odoo odoo12 Odoo13.0 v14
Avatar
Avatar
Avatar
Avatar
4
dic 24
19533
how to particular Sales Order delivery note states using for loop
python odoo odoo12 Odoo13.0
Avatar
0
oct 21
3170
psycopg2.ProgrammingError: no existe la relación «_unknown» Please HELP!!!!
odoo odoo12
Avatar
Avatar
2
nov 25
337
Add New Operation Type in Warehouse Resuelto
odoo Odoo13.0
Avatar
Avatar
Avatar
2
dic 24
5327
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.

Sitio web hecho con

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