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 14: Inherit python method is not working.

Suscribirse

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

Se marcó esta pregunta
stockfunctioninheritancesuperdef
1 Responder
5550 Vistas
Avatar
Muhammad Faheem Khan

I am trying to inherit a method in stock.inventory.line. My issue is, when this method is called from write method, it is working fine (inherited function work), but if I call it from create method, the original function is being used and my inherited function is being ignored.

Original method:

def _check_no_duplicate_line(self):
domain = [
('product_id', 'in', self.product_id.ids),
('location_id', 'in', self.location_id.ids),
'|', ('partner_id', 'in', self.partner_id.ids), ('partner_id', '=', None),
'|', ('package_id', 'in', self.package_id.ids), ('package_id', '=', None),
'|', ('prod_lot_id', 'in', self.prod_lot_id.ids), ('prod_lot_id', '=', None),
'|', ('inventory_id', 'in', self.inventory_id.ids), ('inventory_id', '=', None),
]
groupby_fields = ['product_id', 'location_id', 'partner_id', 'package_id', 'prod_lot_id', 'inventory_id']
lines_count = {}
for group in self.read_group(domain, ['product_id'], groupby_fields, lazy=False):
key = tuple([group[field] and group[field][0] for field in groupby_fields])
lines_count[key] = group['__count']
for line in self:
key = (line.product_id.id, line.location_id.id, line.partner_id.id, line.package_id.id, line.prod_lot_id.id, line.inventory_id.id)
if lines_count[key] > 1:
raise UserError(_("There is already one inventory adjustment line for this product,"
" you should rather modify this one instead of creating a new one."))


Inherited method:


    def _check_no_duplicate_line(self):
res = super(InventoryLine, self)._check_no_duplicate_line()
print('duplicate line called')
_logger.debug('duplicate line verifeid')
# active_id = self.env.context.get('active_id')
# print(active_id)
invent = self.inventory_id.my_custom_field
print(invent)
if invent:
print('in duplicate tag id fond')
return
else:
print('no id found')
return res

write method:

def write(self, vals):
res = super(InventoryLine, self).write(vals)
self._check_no_duplicate_line()
return res

create method:

@api.model_create_multi
def create(self, vals_list):
some code here. . .

res = super(InventoryLine, self).create(vals_list)
res._check_no_duplicate_line()
return res

What could be the reason? Any help will be greatly appreciated.

0
Avatar
Descartar
Avatar
Ibrahim Boudmir
Mejor respuesta

Hi, 

I'm commenting your code generally speaking: 

1- In create function, you're calling bulk create.Therefore, You may have a recordset that's been created. so, you need to loop inside your method.

Using return inside of a loop will break it and exit the function even if the loop is still not finished.

Can you try this instead: 

def _check_no_duplicate_line(self):
    for line in self:
        if not line.inventory_id.my_custom_field:
            super(InventoryLine, line)._check_no_duplicate_line()

Add prints or pdb debug to check.

You can write back for further analysis.
Regards.

1
Avatar
Descartar
Muhammad Faheem Khan
Autor

Thank you for your response.
I tried what you suggested.
I added _logger.debug('called successfully') in your proposed code (loop)
when I called it from write function, I am getting log in terminal "called successfully"
but when I call it for create, I am not even getting this log, but I am getting error in original method. It is really upsetting me.

Ibrahim Boudmir

can you debug code using pdb package and put it (import pdb; pdb.set_trace() ) just after calling super of create function please?

Then print res and click on "s" in order to get into your method...etc
this is how we're going to understand what's happening.
more at: https://docs.python.org/3/library/pdb.html#pdbcommand-next
--------------------------
If all this is "useless", i suggest you use monkey patch : targetting your method in import section, declare all the method and then replace the native with yours.

Muhammad Faheem Khan
Autor

Thank you very much for pointing me the right direction. I don't know what is the issue, but I just tested my custom module on another installation after applying your proposed solution (loop), and it worked fine. I did several tests there. It is working fine, but in old installation, it is still the same. Anyway, +100 for you. I will test it with pdb and post results here later from my effected installation.

Ibrahim Boudmir

Thank you

¿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
Inherit python function
function python inheritance class super
Avatar
Avatar
Avatar
2
may 25
2082
Python "super" - function does not work Resuelto
python inheritance super
Avatar
Avatar
Avatar
2
dic 22
13569
Add/Override parent compute method (event.booth) Odoo15 Resuelto
inheritance super v15
Avatar
Avatar
1
dic 22
4946
Problems overriding the same function from two different modules
function inheritance override
Avatar
0
ene 17
5536
Execution order on inherited functions
function python inheritance
Avatar
0
jul 25
5895
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