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

how to update odoo One2many field from list of dictionaries?

Suscribirse

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

Se marcó esta pregunta
one2manycreateupdateloopdictionary
3 Respuestas
18760 Vistas
Avatar
Mohamed Fouad (personal)

I created a method that loops over all pos orders to get data from there to use it on report, I need to display this data on an One2many field Before printing it, I'm trying a lot but the data created on a model and doesn't displayed on current field

here what I did

data = fields.One2many(comodel_name="onepos.report.line", inverse_name="report", string="", required=False, )

def getreport(self):

    data = self.env['pos.order'].search([])
    datas=[]
    pos_dict= {}
    report= self.env['onepos.report.line'].search([])
    for rec in data:
        con = rec.config_id.name
        for line in rec.lines:
            if con in pos_dict.values():
                print('hiiiiiiiiiii')
                # total_sales = pos_dict[rec.config_id.name]
                total_sales += line.price_subtotal_incl
                res = {
                    'total': total_sales,
                    'pos': con,
                }
                datas.append(res)
            else:
                total_sales = line.price_subtotal_incl
                res2 = {
                    'total': total_sales,
                    'pos': con,
                }
                datas.append(res2)
    if datas:
        print(len(datas), )
        print(datas, )

        cntr = defaultdict(Counter)
        for d in datas:
            cntr[d['pos']].update(d)
        datas = [dict(v, **{'pos': k}) for k, v in cntr.items()]

        report.create(datas)

this is related model

class reporttotalline(models.Model):
_name = 'onepos.report.line'

pos = fields.Char(string="", required=False, )
total = fields.Char(string="", required=False, )

report = fields.Many2one(comodel_name="onepos.report", string="", required=False, )


0
Avatar
Descartar
Jonah Barrett

I am not 100% sure if this is what you are looking for but you might want to try is using the tuple syntax for One2Many / Many2Many fields. (Can be found here)

For example if you were setting One2Many field data:

def getdata(self):

self.write({'data': (0, 0, values_dict)})

This code would create and link a new record to the One2Many field using the values in the values_dict dictionary.

Mohamed Fouad (personal)
Autor

how can assign values_dict or where can i get it

i used

self.write({'data': (0, 0, datas)})

and its return error

if act[0] == 0:

TypeError: 'int' object is not subscriptable

Avatar
Sunray Datalinks Pvt Ltd
Mejor respuesta

hi,

to write to one2many field use :

(0, 0,  { values })    link to a new record that needs to be created with the given values dictionary
(1, ID, { values })    update the linked record with id = ID (write *values* on it)
(2, ID)                remove and delete the linked record with id = ID (calls unlink on ID, that will delete the object completely, and the link to it as well)
(3, ID)                cut the link to the linked record with id = ID (delete the relationship between the two objects but does not delete the target object itself)
(4, ID)                link to existing record with id = ID (adds a relationship)
(5)                    unlink all (like using (3,ID) for all linked records)
(6, 0, [IDs])          replace the list of linked IDs (like using (5) then (4,ID) for each ID in the list of IDs)
0
Avatar
Descartar
Mohamed Fouad (personal)
Autor

i know that , but how to use it in ,my code

i used

self.write({'data': (0, 0, datas)})

and its return error

if act[0] == 0:

TypeError: 'int' object is not subscriptable

¿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
Best way to create one2many records in backend
one2many create update
Avatar
0
nov 22
4961
update one2many field
function one2many create update
Avatar
0
abr 19
4292
[odoo 8 ] : How to update value of one2many field with at second level by using create and write method using API? Resuelto
one2many create update write odooV8
Avatar
Avatar
Avatar
Avatar
6
ago 19
64798
How to update one2many field on write mthod in odoo
one2many update
Avatar
Avatar
1
mar 21
2942
Can not replicate one2many field of one model to other model. Resuelto
one2many create
Avatar
2
abr 20
4888
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