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
    • e-learning
    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
    • Conocimientos
    • 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

CacheMiss: 'mrp.bom.line(459,).product_tmpl_id'

Suscribirse

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

Se marcó esta pregunta
xlsxxls_reportsodoo16Odoo16
1 Responder
1561 Vistas
Avatar
Alark Kulkarni

Hello,

I'm creating xlsx report in Odoo 16 but I'm getting an error message in the logs as  "odoo.exceptions.CacheMiss: 'mrp.bom.line(459,).product_tmpl_id'" followed by "MissingError: Record does not exist or has been deleted. (Record: mrp.bom.line(459,), User: 2)" when report is printed.

My code for xlsx is: 

# -*- coding: utf-8 -*-
from odoo import models, api, _
from odoo.exceptions import UserError

class BomSheetXlsx(models.AbstractModel):
_name = 'report.report_bom_sheet_xls'
_inherit = 'report.report_xlsx.abstract'
_description = 'BOM Sheet Report'

def generate_xlsx_report(self, workbook, data, docs):
# Define formats
bold_format = workbook.add_format(
{'bold': True, 'font_size': 12, 'align': 'center', 'valign': 'vcenter', 'border': 1})
center_format = workbook.add_format({'align': 'center', 'valign': 'vcenter', 'border': 1})

# Create a worksheet
sheet = workbook.add_worksheet('BOM Sheet')

# Fallback for docs if empty
if not docs:
record_ids = data.get('active_ids', [])
docs = self.env['your_model_name'].browse(record_ids).sudo().exists() # Ensure model is correct

# Print document IDs for debugging
print("Docs after fallback and sudo:", docs.ids)

# Display Project Name
project_name = 'Unknown Project'
for obj in docs:
if hasattr(obj, 'product_tmpl_id') and obj.product_tmpl_id:
project_name = obj.product_tmpl_id.name or 'Unknown Product'
else:
project_name = 'Unknown Project'

sheet.merge_range(0, 0, 0, 3, f'Project: {project_name}', bold_format)

# Merged header for project details
sheet.merge_range('A2:D2', 'Project Details', bold_format)

# Define and write Project Lines Table Header
project_headers = [
'Product (Finished Good)',
'Product Quantity',
'Total Cost',
'Unit Cost'
]

for col_num, header in enumerate(project_headers):
sheet.write(2, col_num, header, bold_format)

# Fetch project lines, ensuring valid records exist
project_lines = self.env['mrp.project.lines'].sudo().search([('project_product_id', 'in', docs.ids)])

print("Project Lines Count:", len(project_lines)) # Debugging line

row_num = 3 # Start from row 3 for data
if project_lines:
for line in project_lines:
# Safely access fields and handle CacheMiss errors
try:
product_name = line.product_id.name if line.product_id else ''
sheet.write(row_num, 0, product_name, center_format)
sheet.write(row_num, 1, line.product_quantity, center_format)
sheet.write(row_num, 2, line.total_cost, center_format)
sheet.write(row_num, 3, line.product_unit_cost, center_format)
row_num += 1
except Exception as e:
print(f"Error accessing line data: {e}") # Log the error

# Calculate the row to start the BOM section
last_project_row = row_num
sheet.write(last_project_row, 0, '', center_format) # Blank row

# Merged header for BOM section
bom_header_row = last_project_row + 1 # Adjust row index for the BoM header
sheet.merge_range(bom_header_row, 0, bom_header_row, 10, 'Bill of Material (BoM)', bold_format)

# Define and write BOM headers
headers = [
'Finished Good', 'Semi-Finished Good', 'Raw Material', 'Qty', 'Unit of Measure',
'Std. Unit Price', 'Unit Cost', 'Ideal Qty', 'Ideal Cost', 'Order Qty', 'Min Order Qty'
]
for col_num, header in enumerate(headers):
sheet.write(bom_header_row + 1, col_num, header, bold_format)

# Fetch and write BOM lines
bom_lines = self.env['mrp.bom.line'].sudo().search([('bom_id', 'in', docs.ids)])

print("BOM Lines Count:", len(bom_lines)) # Debugging line

row_num = bom_header_row + 2 # Start from row after headers
if bom_lines:
for line in bom_lines:
try:
# Safely access fields and handle CacheMiss errors
finished_good = line.life_fg.name if line.life_fg else ''
semi_finished_good = line.model_sfg.name if line.model_sfg else ''
raw_material = line.product_id.name if line.product_id else ''
qty = line.life_qty
uom = line.product_uom_id.name if line.product_uom_id else ''
std_unit_price = line.life_uom
unit_cost = line.life_unit_cost
ideal_qty = line.product_qty
ideal_cost = line.life_ideal_cost
order_qty = line.life_order_qty
min_order_qty = line.life_min_qty

sheet.write(row_num, 0, finished_good, center_format)
sheet.write(row_num, 1, semi_finished_good, center_format)
sheet.write(row_num, 2, raw_material, center_format)
sheet.write(row_num, 3, qty, center_format)
sheet.write(row_num, 4, uom, center_format)
sheet.write(row_num, 5, std_unit_price, center_format)
sheet.write(row_num, 6, unit_cost, center_format)
sheet.write(row_num, 7, ideal_qty, center_format)
sheet.write(row_num, 8, ideal_cost, center_format)
sheet.write(row_num, 9, order_qty, center_format)
sheet.write(row_num, 10, min_order_qty, center_format)
row_num += 1
except Exception as e:
print(f"Error accessing BOM line data: {e}") # Log the error

# Adjust column widths if necessary
sheet.set_column('A:K', 23) # Adjust column width for all columns if necessary
0
Avatar
Descartar
Avatar
J.A. Daniel Göppner
Mejor respuesta

The error you're encountering (CacheMiss and MissingError) indicates that the code is trying to access a record in mrp.bom.line that does not exist or has been deleted, and Odoo’s cache is unable to find this record.

Here are some modifications and improvements that might resolve these issues:

  1. Check for Record Existence: Use the .exists() method on bom_lines to ensure you’re working only with valid, existing records. This will prevent errors if a record has been deleted or is otherwise inaccessible.
  2. Refine Access to Fields: Wrap each record access in a try-except block, as you’ve partially done, to handle any CacheMiss exceptions gracefully and ensure they are not disruptive to the report generation.
  3. Adjust Record Access for Specific Fields: product_tmpl_id might be causing the CacheMiss. Ensure any related field you’re accessing exists by using if hasattr(line, 'product_tmpl_id').

Also you are applying sudo for the search bom_lines = self.env['mrp.bom.line'].sudo().search([('bom_id', 'in', docs.ids)]), if you are in multi company env or have restricted access to some BoM's you will get teh records, but in the next iteration the odoo access check will be applied. That could be also the issue


Hope this helps

1
Avatar
Descartar
¿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
Morning fam! Can someone please help me understand why the header in my custom pdf report is overlapping the content of the report page on multiple pages?
qweb-report odoo16 Odoo16
Avatar
1
jun 24
1564
Custom "Download xlsx" feature in pivot view
xls_reports pivotreport Attendances odoo16
Avatar
0
ene 25
1201
How to save XLSX file to ir_attachment Resuelto
xlsx xls_reports xlsxwriter v15
Avatar
Avatar
1
may 22
6656
XLSX Report should be shown in single sheet for Odoo10.
xlsx odoo xls_reports odoo10
Avatar
Avatar
1
jul 19
5628
how to create xls report for the sale.order?
customization sale.order xlsx xls xls_reports
Avatar
Avatar
Avatar
2
jun 23
9516
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