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
    • eLearning
    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
    • Información
    • 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

Odoo 13 : Problems with one2many/many2one filters

Suscribirse

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

Se marcó esta pregunta
many2oneone2manyFiltersOdoo13
1 Responder
2282 Vistas
Avatar
Tessa Roberts

Hello everyone !


I'm having problems creating filters for "one2many" and "many2one" fields.


For one of the projects I'm working on in Odoo v13, there is a custom model named "res.partner.contact".


In the "res.partner" model definition, a "one2many" field of type "res.partner.contact" has been added. 

This field is called "contacts" and is labelled "Partner contacts". 

This new "res.partner.contact" model contains the contact's name, date of birth and relationship to the "res.partner". And a "many2one" field of type "res.partner".


"res.partner" model definition


class ResPartner(models.Model):
    _inherit = "res.partner"
    _description="Partners"
    [...]
  contacts = fields.One2many('res.partner.contact', 'partner_id',string='Partner contacts')
   [...]



"res.partner.contact" model definition


class ResPartnerContact(models.Model): 
_name = 'res.partner.contact'
    _description = "Contacts"
    [...]
    name = fields.Char(string="Name")    
    birthdate = fields.Date(string="Birthdate")
    partner_id = fields.Many2one('res.partner', string='Partner', ondelete='cascade')
[...]


In the definition of the "res.partner" search view, I'd like to add a filter to filter partners by it's contacts date of birth. 

In fact, I want to filter out all partners whose contact's date of birth falls between two given dates. 


I've tried several different filter definitions, but the wrong partners are filtered out. 

(The contacts of the filtered partners have a date of birth outside the given date range).


Example of one the filter's domain I tried to declare in the res.partner search view

domain="[('contacts.birthdate', '>=', time.strftime('2019-07-31')),('contacts.birthdate', '<=', time.strftime('2020-08-01'))]"


When I apply this filter, literally one of the first results in the list of filtered "res.partner" contains a single contact whose date of birth is "2019-05-12". So the filter doesn't work.


If I put only one of the conditions in the domain, the filter works correctly.

The "&" operation does not appear to perform the join between the two conditions.


I can't add a field with fixed dates to facilitate the filter in the "res.partner.contact" model because these dates are likely to change from one year to the next.


Has anyone created filters with similar functionality?

Do you have any idea what I could do to achieve my goal, if possible?


Thank you in advance,


Mélanie


0
Avatar
Descartar
Avatar
Tessa Roberts
Autor Mejor respuesta

Hi everyone,


Here's what I ended up doing to "solve" my problem.

I added a computed boolean field in the "res.partner.contact" model.


in_date_range = fields.Boolean('In date range', compute=_compute_field, search="_search_field")


Here are the compute and search functions for this field : 


     from datetime import datetime, date

def _compute_field(self):
        date_from = datetime.strptime('2019-08-01', "%Y-%m-%d")
        date_to = datetime.strptime('2020-07-31', "%Y-%m-%d")
        for record in self:
            if record.birthdate != False and record.birthdate >= date_from.date() and record.birthdate and record.in_date_range = True
            else:
                record.in_date_range = False
    def _search_field(self, operator, value):
        recs = self.search([]).filtered(lambda x : x.in_date_range is True)
        if recs:
            return [('id', 'in', [x.id for x in recs])]


In the search view of the "res.partner" model, I've added a filter with the following domain:


domain="[('contacts.in_date_range', '=', True)]"


I would have preferred to be able to search directly by dates, but that doesn't seem possible and this solution works.

The next step will be to make the search function dynamic by allowing the user to enter dates.


I'm going to close this post.

If by some miracle I find another solution, I might come and update it if I can.


Goodbye


0
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
Create/Update: a mandatory field is not set
error many2one one2many Odoo13 mandatory-field
Avatar
Avatar
1
oct 23
3916
How do I put One2many after Many2one defined? - transient module states reset
many2one one2many
Avatar
1
mar 23
3206
Odoo Studio how to set a chain of multiple and related Many2one within a One2many lines
many2one one2many
Avatar
0
dic 22
3807
Automatically open many2one or one2many field without clicking external link icon
code many2one one2many Odoo13 odoo13
Avatar
0
oct 22
2771
filter according to comodel's fields
many2one one2many
Avatar
0
jun 21
3513
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