Update api/reports/views.py
This commit is contained in:
@@ -235,19 +235,14 @@ class ExportDataStageView(APIView):
|
|||||||
# 🔥 APLICAR FILTROS RELACIONADOS
|
# 🔥 APLICAR FILTROS RELACIONADOS
|
||||||
filters = self.apply_related_filters(global_filters, model, related_keys, request.user)
|
filters = self.apply_related_filters(global_filters, model, related_keys, request.user)
|
||||||
|
|
||||||
print(f"🎯 FILTROS APLICADOS A {model_name}: {filters}")
|
|
||||||
|
|
||||||
# Si hay filtros, aplicarlos; si no, obtener todos los registros
|
# Si hay filtros, aplicarlos; si no, obtener todos los registros
|
||||||
if filters:
|
if filters:
|
||||||
queryset = model.objects.filter(**filters).values(*fields)
|
queryset = model.objects.filter(**filters).values(*fields)
|
||||||
else:
|
else:
|
||||||
queryset = model.objects.none() # No obtener nada si no hay filtros
|
queryset = model.objects.none() # No obtener nada si no hay filtros
|
||||||
|
|
||||||
print(f"📊 {model_name}: {queryset.count()} registros después de filtrado relacionado")
|
|
||||||
|
|
||||||
# Si no hay registros, saltar este modelo
|
# Si no hay registros, saltar este modelo
|
||||||
if queryset.count() == 0:
|
if queryset.count() == 0:
|
||||||
print(f"🔶 {model_name}: Sin registros después de filtrado, saltando...")
|
|
||||||
continue
|
continue
|
||||||
|
|
||||||
# Crear hoja (limitar nombre a 31 caracteres)
|
# Crear hoja (limitar nombre a 31 caracteres)
|
||||||
@@ -267,7 +262,6 @@ class ExportDataStageView(APIView):
|
|||||||
ws.append(row_values)
|
ws.append(row_values)
|
||||||
|
|
||||||
except LookupError:
|
except LookupError:
|
||||||
print(f"Modelo {model_name} no encontrado")
|
|
||||||
continue
|
continue
|
||||||
|
|
||||||
# Si no se crearon hojas, crear una vacía
|
# Si no se crearon hojas, crear una vacía
|
||||||
@@ -313,7 +307,6 @@ class ExportDataStageView(APIView):
|
|||||||
total_records = queryset.count()
|
total_records = queryset.count()
|
||||||
|
|
||||||
if total_records == 0:
|
if total_records == 0:
|
||||||
print(f"🔶 {model_name}: Sin registros, saltando...")
|
|
||||||
continue
|
continue
|
||||||
|
|
||||||
if total_records > self.MAX_RECORDS_PER_FILE:
|
if total_records > self.MAX_RECORDS_PER_FILE:
|
||||||
@@ -694,15 +687,12 @@ class ExportDataStageView(APIView):
|
|||||||
filters = {}
|
filters = {}
|
||||||
model_fields = [f.name for f in model._meta.get_fields()]
|
model_fields = [f.name for f in model._meta.get_fields()]
|
||||||
|
|
||||||
print(f"🔍 APLICANDO FILTROS RELACIONADOS PARA: {model.__name__}")
|
|
||||||
print(f"🔍 CLAVES RELACIONADAS DISPONIBLES: {related_keys}")
|
|
||||||
|
|
||||||
# 🔥 ESTRATEGIA MEJORADA: Usar claves relacionadas SI HAY, sino aplicar filtros directos SOLO si existen
|
# 🔥 ESTRATEGIA MEJORADA: Usar claves relacionadas SI HAY, sino aplicar filtros directos SOLO si existen
|
||||||
has_related_keys = any(related_keys.values())
|
has_related_keys = any(related_keys.values())
|
||||||
|
|
||||||
if has_related_keys:
|
if has_related_keys:
|
||||||
# 🔥 MODO RELACIONADO ESTRICTO: Usar SOLO las claves obtenidas
|
# 🔥 MODO RELACIONADO ESTRICTO: Usar SOLO las claves obtenidas
|
||||||
print("🎯 MODO RELACIONADO ACTIVO - FILTRANDO POR CLAVES COMUNES")
|
|
||||||
|
|
||||||
# Crear condiciones para las claves relacionadas
|
# Crear condiciones para las claves relacionadas
|
||||||
from django.db.models import Q
|
from django.db.models import Q
|
||||||
@@ -711,60 +701,39 @@ class ExportDataStageView(APIView):
|
|||||||
|
|
||||||
if related_keys.get('patentes') and 'patente' in model_fields:
|
if related_keys.get('patentes') and 'patente' in model_fields:
|
||||||
filters['patente__in'] = related_keys['patentes']
|
filters['patente__in'] = related_keys['patentes']
|
||||||
print(f"✅ FILTRO PATENTE RELACIONADO: {len(related_keys['patentes'])} patentes")
|
|
||||||
has_related_conditions = True
|
has_related_conditions = True
|
||||||
|
|
||||||
if related_keys.get('pedimentos') and 'pedimento' in model_fields:
|
if related_keys.get('pedimentos') and 'pedimento' in model_fields:
|
||||||
filters['pedimento__in'] = related_keys['pedimentos']
|
filters['pedimento__in'] = related_keys['pedimentos']
|
||||||
print(f"✅ FILTRO PEDIMENTO RELACIONADO: {len(related_keys['pedimentos'])} pedimentos")
|
|
||||||
has_related_conditions = True
|
has_related_conditions = True
|
||||||
|
|
||||||
if related_keys.get('datastage_ids') and 'datastage_id' in model_fields:
|
if related_keys.get('datastage_ids') and 'datastage_id' in model_fields:
|
||||||
filters['datastage_id__in'] = related_keys['datastage_ids']
|
filters['datastage_id__in'] = related_keys['datastage_ids']
|
||||||
print(f"✅ FILTRO DATASTAGE RELACIONADO: {len(related_keys['datastage_ids'])} IDs")
|
|
||||||
has_related_conditions = True
|
has_related_conditions = True
|
||||||
|
|
||||||
# Si NO HAY condiciones relacionadas para este modelo (no tiene los campos)
|
# Si NO HAY condiciones relacionadas para este modelo (no tiene los campos)
|
||||||
if not has_related_conditions:
|
if not has_related_conditions:
|
||||||
print(f"⚠️ {model.__name__} no tiene campos para aplicar filtros relacionados - RETORNANDO VACÍO")
|
|
||||||
return {} # Retornar filtro vacío hará que no se obtengan registros
|
return {} # Retornar filtro vacío hará que no se obtengan registros
|
||||||
|
|
||||||
else:
|
else:
|
||||||
# 🔥 MODO DIRECTO: No hay claves relacionadas, aplicar filtros directos SOLO si existen
|
# 🔥 MODO DIRECTO: No hay claves relacionadas, aplicar filtros directos SOLO si existen
|
||||||
print("🎯 MODO DIRECTO - APLICANDO FILTROS INDIVIDUALES")
|
|
||||||
|
|
||||||
if 'organizacion' in model_fields and global_filters.get('organizacion'):
|
if 'organizacion' in model_fields and global_filters.get('organizacion'):
|
||||||
filters['organizacion'] = global_filters['organizacion']
|
filters['organizacion'] = global_filters['organizacion']
|
||||||
print(f"✅ FILTRO ORGANIZACIÓN DIRECTO: {global_filters['organizacion']}")
|
|
||||||
|
|
||||||
if 'patente' in model_fields and global_filters.get('patente'):
|
if 'patente' in model_fields and global_filters.get('patente'):
|
||||||
filters['patente'] = global_filters['patente']
|
filters['patente'] = global_filters['patente']
|
||||||
print(f"✅ FILTRO PATENTE DIRECTO: {global_filters['patente']}")
|
|
||||||
|
|
||||||
if 'pedimento' in model_fields and global_filters.get('pedimento'):
|
if 'pedimento' in model_fields and global_filters.get('pedimento'):
|
||||||
filters['pedimento'] = global_filters['pedimento']
|
filters['pedimento'] = global_filters['pedimento']
|
||||||
print(f"✅ FILTRO PEDIMENTO DIRECTO: {global_filters['pedimento']}")
|
|
||||||
|
|
||||||
if 'rfc' in model_fields and global_filters.get('rfc'):
|
if 'rfc' in model_fields and global_filters.get('rfc'):
|
||||||
filters['rfc'] = global_filters['rfc']
|
filters['rfc'] = global_filters['rfc']
|
||||||
print(f"✅ FILTRO RFC DIRECTO: {global_filters['rfc']}")
|
|
||||||
|
|
||||||
# 🔥 APLICAR ORGANIZACIÓN SIEMPRE si existe (en ambos modos)
|
# 🔥 APLICAR ORGANIZACIÓN SIEMPRE si existe (en ambos modos)
|
||||||
if 'organizacion' in model_fields and global_filters.get('organizacion'):
|
if 'organizacion' in model_fields and global_filters.get('organizacion'):
|
||||||
filters['organizacion'] = global_filters['organizacion']
|
filters['organizacion'] = global_filters['organizacion']
|
||||||
print(f"✅ FILTRO ORGANIZACIÓN: {global_filters['organizacion']}")
|
|
||||||
|
|
||||||
# 🔥 APLICAR FILTROS DE FECHA SIEMPRE (si el campo existe)
|
# 🔥 APLICAR FILTROS DE FECHA SIEMPRE (si el campo existe)
|
||||||
if 'fecha_pago_real' in model_fields:
|
if 'fecha_pago_real' in model_fields:
|
||||||
if global_filters.get('fecha_pago_desde'):
|
if global_filters.get('fecha_pago_desde'):
|
||||||
filters['fecha_pago_real__gte'] = global_filters['fecha_pago_desde']
|
filters['fecha_pago_real__gte'] = global_filters['fecha_pago_desde']
|
||||||
print(f"✅ FILTRO FECHA DESDE: {global_filters['fecha_pago_desde']}")
|
|
||||||
|
|
||||||
if global_filters.get('fecha_pago_hasta'):
|
if global_filters.get('fecha_pago_hasta'):
|
||||||
filters['fecha_pago_real__lte'] = global_filters['fecha_pago_hasta']
|
filters['fecha_pago_real__lte'] = global_filters['fecha_pago_hasta']
|
||||||
print(f"✅ FILTRO FECHA HASTA: {global_filters['fecha_pago_hasta']}")
|
|
||||||
|
|
||||||
print(f"🎯 FILTROS FINALES PARA {model.__name__}: {filters}")
|
|
||||||
|
|
||||||
return filters
|
return filters
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user