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

Get product's concatenated attributes in python model

Suscribirse

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

Se marcó esta pregunta
pythoncoding
2 Respuestas
4444 Vistas
Avatar
Parker D

Hello there :)

I have a little custom made app that exports product variant's data to a CSV file and now, I'd like to add their attributes. When I export product variants directly through Odoo and I add the column "product_template_attribute_value_ids", I get the attribute names and values as a text, for example "Size: XXL, Color: red" for a t-shirt.

Unfortunately I do not know how to get this data through my script. 

Here is a simplified version of my script, including my latest try to get the attributes:

with tempfile.NamedTemporaryFile(prefix="product data", suffix=".csv") as data_file:
headers = ['ID', 'Internal Reference', 'Name', 'German Name', 'Attributes', 'Attributes German','GTIN / EAN']
writer = pycompat.csv_writer(data_file, quoting=1)
writer.writerow(headers)
product_ids = product_obj.search([])
for product in product_ids:
english_product_name = product.with_context({'lang': 'en_US'}).name
german_product_name = product.with_context({'lang': 'de_DE'}).name

# trying to get the attributes starts here
english_attributes = ''
german_attributes = ''
for attributes in product.attribute_line_ids:
for attribute_values in attributes.product_template_value_ids:
english_attributes += attribute_values.with_context({'lang': 'en_US'}) + ','
german_attributes += attribute_values.with_context({'lang': 'de_DE'}) + ','
# trying to get the attributes ends here

writer.writerow(
[product.id, product.default_code, english_product_name, german_product_name, english_attributes, german_attributes, product.barcode])

This does not work and instead of the actual attributes of the particular variant, this lists all the attribute's values of the product's template, e.g. "S,L,XL,XXL,XXXL,blue,red,green,black,yellow,". 

Does anyone know how to get the attribute's names and value for each product's variant?

0
Avatar
Descartar
Avatar
Parker D
Autor Mejor respuesta

I've finally found it! 😁
The pre-made string can be found in "product_template_attribute_value_ids" of the product.product data model. This relates to this model "product.template.attribute.value", which has the desired string in the column "display_name". 
Here is my adjusted code: 

   # trying to get the attributes starts here
english_attributes = ''
german_attributes = ''
eng_attrs = []
de_attrs = []
 for attribute in product.product_template_attribute_value_ids:
    eng_attrs.append(attribute.with_context({'lang': 'en_US'}).display_name)
de_attrs.append(attribute.with_context({'lang': 'de_DE'}).display_name)
english_attributes = ', '.join(eng_attrs)
german_attributes = ', '.join(de_attrs)
# trying to get the attributes ends here

This delivers the exact string I was looking for. The yellow t-shirt in XXL has the string "Size: XXL, Color: yellow" in English and the correct translation in German. 

Thanks again, @Cybrosis.

0
Avatar
Descartar
Avatar
Cybrosys Techno Solutions Pvt.Ltd
Mejor respuesta

Hi,

Try the following code. I have changed some of your variable names.

for product in product_ids:
english_product_name = product.with_context({'lang': 'en_US'}).name
german_product_name = product.with_context({'lang': 'de_DE'}).name

# trying to get the attributes starts here
english_attributes = ''
german_attributes = ''
eng_attrs = []
de_attrs = []
for attribute in product.attribute_line_ids:
for attribute_value in attribute.product_template_value_ids:
eng_attrs.append(attribute_value.attribute_id.with_context(
{'lang': 'en_US'}).name + ': ' + attribute_value.with_context(
{'lang': 'en_US'}).name)
de_attrs.append(attribute_value.attribute_id.with_context(
{'lang': 'de_DE'}).name + ': ' + attribute_value.with_context(
{'lang': 'de_DE'}).name)
english_attributes = ', '.join(eng_attrs)
german_attributes = ', '.join(de_attrs)
# trying to get the attributes ends here

Regards

0
Avatar
Descartar
Parker D
Autor

Hi Cybrosys and thank you! But unfortunately this also adds all possible attribute values of the product template as well, not those of the variant.

Instead of this: "S,L,XL,XXL,XXXL,blue,red,green,black,yellow,"

I now get this: "Size: S, Size: L, Size: XL, Size: XXL, Size: XXXL, Color: blue, Color: red, Color: green [...]".

I guess, I could adjust it, so the attribute name would only appear once, but I still have the problem to narrow the attributes and their values down to those used on the individual variant.
Any ideas?

Parker D
Autor

I forgot to mention, that I use Odoo 14 Enterprise.

¿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
new python env
python
Avatar
0
mar 25
2473
What means "Too many values to unpack" message? Resuelto
python
Avatar
Avatar
Avatar
Avatar
Avatar
4
abr 24
176136
have no data in screen. read data in my own module from different model
python
Avatar
0
dic 23
3087
How to insert value to a one2many field in table with create method? Resuelto
python
Avatar
Avatar
Avatar
Avatar
Avatar
5
jul 25
232737
how to disable add product in sales of odoo 12
python
Avatar
Avatar
1
dic 22
4287
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