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]How to Migrate sql injection to ORM (self.env) to update another model?

Suscribirse

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

Se marcó esta pregunta
orminjectionodoo10self.write
1 Responder
8076 Vistas
Avatar
FEDERICO LEONI

Now that I've migrated all my python stuff on a module under Odoo I would like to clean a bit more my code starting to pull out all the lines that are writing to others models using self.env.cr.execute, not secure as a native self.write.

I' ve read the docs and I' ve seen there is a way to call another recordset using self.env.context but I did not find a clear solution to write from a model to another.

For example in a model A I need to write in model B with

sql_record_cst = 'INSERT INTO modelB (curr_day, ord_proc) values(%s, 1)'
self.env.cr.execute(sql_record_cst,[self.fieldinmodelA])
self.env.cr.commit()

What should be the equivalent solution using ORM?
First thing of, I should change the target model, then I should be able to change the value of the field with a simple self.field=value or self.write({'fieldA' : value,  'fieldB' : value}).

What I' ve tried:

(in pos.config)
if self.sequence_number == 1:
   self.env.cr.execute(sql_test_session,[str(self.start_at[0:10]+'%')])
   curr_day = self.env.cr.fetchone()
   if curr_day is None:
       today_d = str(self.start_at[0:10])
       self.env['divina.custos'].create({'curr_day':today_d,'ord_proc':1}

But I get the error:

File "/odoo_dv/odoo_dv-server/addons/point_of_sale/models/pos_config.py", line 256, in open_session_cb 'config_id': self.id File "/odoo_dv/odoo_dv-server/addons/point_of_sale/models/pos_session.py", line 196, in create res.action_pos_session_open() File "/odoo_dv/odoo_dv-server/addons/point_of_sale/models/pos_session.py", line 222, in action_pos_session_open session.write(values) File "/odoo_dv/odoo_dv-server/odoo/models.py", line 3550, in write self._write(old_vals) File "/odoo_dv/odoo_dv-server/odoo/models.py", line 3758, in _write self.recompute() File "/odoo_dv/odoo_dv-server/odoo/models.py", line 5287, in recompute vals = rec._convert_to_write({n: rec[n] for n in ns}) File "/odoo_dv/odoo_dv-server/odoo/models.py", line 5287, in <dictcomp> vals = rec._convert_to_write({n: rec[n] for n in ns}) File "/odoo_dv/odoo_dv-server/odoo/models.py", line 5186, in __getitem__ return self._fields[key].__get__(self, type(self)) File "/odoo_dv/odoo_dv-server/odoo/fields.py", line 872, in __get__ value = record._cache[self] File "/odoo_dv/odoo_dv-server/odoo/models.py", line 5534, in __getitem__ value = self._recs.env.cache[field][self._recs.id]
KeyError: 3

 And if I try to force the field date (test purpouse) with

self.env['divina.custos'].create({'curr_day':'2017-02-21 00:00:00','ord_proc':1})

I get another error

File "/odoo_dv/odoo_dv-server/odoo/models.py", line 5534, in __getitem__ value = self._recs.env.cache[field][self._recs.id]KeyError: 4
So I think I' m on the right path, I just need to learn the correct  syntax. 
Please note that 
self.env[model.name'].search or self.env['model.name'].browse

works juts fine.

0
Avatar
Descartar
Avatar
Pawan
Mejor respuesta

Federico,

Here are the some of thing which might interest you:

  •  For getting the link/access to other model we use :
    self.env['model.name'] (in new api)
    self.pool.get('model.name') ('in old api)

  • from model A, if you want to create record in model B use:
    self.env['b'].create({'key1':'val','key2':val})

  • from model A, if you want to update some field of record 'x' in model B:
    self.env['b'].write(x, {'key1':'val','key2':val})

Hope it helps!!

1
Avatar
Descartar
FEDERICO LEONI
Autor

Yeah, helped a lot, even if I still have some difficult to understand the syntax like

today_d = str(self.start_at[0:10])

self.env['divina.custos'].create({'curr_day':today_d,'ord_proc':1}

that is giving error. But I' m almost there!

I' ve updated my OP with one more little piece of code.

Pawan

What error are you getting?

FEDERICO LEONI
Autor

Is on the OP, the most common is

File "/odoo_dv/odoo_dv-server/odoo/models.py", line 5186, in __getitem__ return self._fields[key].__get__(self, type(self)) File "/odoo_dv/odoo_dv-server/odoo/fields.py", line 872, in __get__ value = record._cache[self] File "/odoo_dv/odoo_dv-server/odoo/models.py", line 5534, in __getitem__ value = self._recs.env.cache[field][self._recs.id]

KeyError: 3

¿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
[odoo10]weird issue with self.write
orm odoo10 self.write
Avatar
0
mar 17
3926
[odoo10] self.env.search_read find a field, simple search does not. Resuelto
orm odoo10 self.env.search
Avatar
Avatar
1
mar 17
12660
[Odoo 10] .write() stop working and rise error value = self._recs.env.cache[field][self._recs.id] Resuelto
python records odoo10 self.write
Avatar
Avatar
Avatar
5
jul 20
9829
raise ValueError(“Expected singleton: %s” % self) when return more than one record Resuelto
orm refund python2.7 odoo10
Avatar
Avatar
1
dic 19
6648
[SOLVED][Odoo 10] self.env[].search: how to return multiple field in a list? Resuelto
python orm search self odoo10
Avatar
Avatar
5
sept 20
63819
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