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

Python: Retrieving filtered records

Suscribirse

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

Se marcó esta pregunta
filterpythonv18
3 Respuestas
2031 Vistas
Avatar
Tessa Roberts

Hello,


Is there a way to retrieve, in python, the domain of active filters in the list view or the list of record IDs displayed in the list view?


I have a search function on a custom field and in this function, I would like to call a function on the IDs of the list of records displayed in the list view.


I've tried looking in the context but there's no parameter similar to “active_ids”.


Is this possible?


Thank you

0
Avatar
Descartar
Christoph Farnleitner

First, great you took the time to updated your post with your findings! Apart from that, I'm unsure about your usecase. For doing something based on records visible I would usually rather consider a computed field that is not stored. Also, as said, unsure about your usecase, but search, read, read_group etc all are functions on odoo.models (like create, write, etc) and can be extended per model. The search function for example has this definition: def search(self, domain, offset=0, limit=None, order=None) -> Self

Avatar
Tessa Roberts
Autor Mejor respuesta

I've found a way to get the active domain.

However, I think there must still be a better way to solve the problem.


In the browser inspector, I studied the http requests sent and received when a filter was activated.

The request looks something like this:

{
"jsonrpc":"2.0",
"method":"call",
"params":{
"model":"crm.lead",
"domain":[["type","=","opportunity"],["date",">=","2019-04-18"]],
"fields":["partner_id","user_id","phone","categs_id","state",],
"limit":80,
"sort":"create_date DESC",
"context":{
"lang":"fr_FR",
"tz":"Europe/Paris",
"uid":31,
"allowed_company_ids":[1],
"params":{"action":1647,"model":"crm.lead","view_type":"list","cids":"","menu_id":451},
"stage_type":"opportunity",
"default_type":"opportunity",
"default_user_id":31,
"needaction_menu_ref":"sale.menu_sale_quotations",
"bin_size":true
}
},"id":393865456
}


I was able to recover the active domain by importing “request” from odoo.http


from odoo.http import request


And then, in the source code of my python function :


http_request_domain = request.params.get('domain')


Based on all this, I think I'll be able to retrieve the list of record ids corresponding to the domain and achieve my goal.


Have a nice day

1
Avatar
Descartar
Avatar
Cybrosys Techno Solutions Pvt.Ltd
Mejor respuesta

Hi,


In Odoo 17, you can retrieve the active filters (domain) in a list view and also access the records currently visible using the following method.

from odoo import models, api

class YourModel(models.Model):

    _inherit = 'your.model'


    @api.model

    def web_search_read(self, domain, fields, offset=0, limit=None, order=None, count_limit=None):

        # Domain contains the active filters in the list view

        print("Active domain (filters):", domain)

        # Fetch records visible in the list view

        records = self.search_read(domain, fields, offset=offset, limit=limit, order=order)

        print("Visible records:", records)

        # Proceed with the original behavior

        return super().web_search_read(domain, fields, offset=offset, limit=limit, order=order, count_limit=count_limit)


Hope it helps

0
Avatar
Descartar
Avatar
Odiware Technologies
Mejor respuesta

Hey there!

I totally get what you're trying to do - this is actually a pretty common challenge in Odoo development. You want to grab either the current domain filters or the list of record IDs that are showing in your list view from within a custom search function. The tricky part is that when you're inside a search method, you're kind of "in the middle" of the search process, so the usual active_ids approach doesn't work here.


If you can control when your search function gets called, you can pass the domain through the context:

python

# In your custom search method
def _search_your_field(self, operator, value):
    context = self.env.context
    current_domain = context.get('search_default_domain', [])
    
    # Now you can work with the current domain
    # and call your function with the relevant IDs
    if current_domain:
        filtered_records = self.search(current_domain)
        your_custom_function(filtered_records.ids)
    
    # Return your search domain
    return [('your_field', operator, value)]

0
Avatar
Descartar
¿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
Filters with multiple conditions
filter python deliveryorder
Avatar
0
nov 24
1948
How i can apply filter into record ?
filter python orm
Avatar
Avatar
1
sept 19
2952
[✅ SOLVED] How to make sure odoo.addons.base.models.ir_cron will log the number of processed records on a cronjob completion ?
python cronjob entreprise v18
Avatar
0
jul 25
1603
Problem with date filter BETWEEN two dates
filter date between v18
Avatar
Avatar
Avatar
2
may 25
2001
[✅ SOLVED] How to extend a XML search filter view and add an additional filter ? Resuelto
filter searchview xmlview v18
Avatar
Avatar
1
may 25
3577
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.

Sitio web hecho con

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