Skip to Content
Odoo Menú
  • Registra entrada
  • Prova-ho gratis
  • Aplicacions
    Finances
    • Comptabilitat
    • Facturació
    • Despeses
    • Full de càlcul (IA)
    • Documents
    • Signatura
    Vendes
    • CRM
    • Vendes
    • Punt de venda per a botigues
    • Punt de venda per a restaurants
    • Subscripcions
    • Lloguer
    Imatges de llocs web
    • Creació de llocs web
    • Comerç electrònic
    • Blog
    • Fòrum
    • Xat en directe
    • Aprenentatge en línia
    Cadena de subministrament
    • Inventari
    • Fabricació
    • PLM
    • Compres
    • Manteniment
    • Qualitat
    Recursos humans
    • Empleats
    • Reclutament
    • Absències
    • Avaluacions
    • Recomanacions
    • Flota
    Màrqueting
    • Màrqueting Social
    • Màrqueting per correu electrònic
    • Màrqueting per SMS
    • Esdeveniments
    • Automatització del màrqueting
    • Enquestes
    Serveis
    • Projectes
    • Fulls d'hores
    • Servei de camp
    • Suport
    • Planificació
    • Cites
    Productivitat
    • Converses
    • Validacions
    • IoT
    • VoIP
    • Coneixements
    • WhatsApp
    Aplicacions de tercers Odoo Studio Plataforma d'Odoo al núvol
  • Sectors
    Comerç al detall
    • Llibreria
    • Botiga de roba
    • Botiga de mobles
    • Botiga d'ultramarins
    • Ferreteria
    • Botiga de joguines
    Food & Hospitality
    • Bar i pub
    • Restaurant
    • Menjar ràpid
    • Guest House
    • Distribuïdor de begudes
    • Hotel
    Immobiliari
    • Agència immobiliària
    • Estudi d'arquitectura
    • Construcció
    • Gestió immobiliària
    • Jardineria
    • Associació de propietaris de béns immobles
    Consultoria
    • Empresa comptable
    • Partner d'Odoo
    • Agència de màrqueting
    • Bufet d'advocats
    • Captació de talent
    • Auditoria i certificació
    Fabricació
    • Textile
    • Metal
    • Mobles
    • Menjar
    • Brewery
    • Regals corporatius
    Salut i fitness
    • Club d'esport
    • Òptica
    • Centre de fitness
    • Especialistes en benestar
    • Farmàcia
    • Perruqueria
    Trades
    • Servei de manteniment
    • Hardware i suport informàtic
    • Sistemes d'energia solar
    • Shoe Maker
    • Serveis de neteja
    • Instal·lacions HVAC
    Altres
    • Nonprofit Organization
    • Agència del medi ambient
    • Lloguer de panells publicitaris
    • Fotografia
    • Lloguer de bicicletes
    • Distribuïdors de programari
    Browse all Industries
  • Comunitat
    Aprèn
    • Tutorials
    • Documentació
    • Certificacions
    • Formació
    • Blog
    • Pòdcast
    Potenciar l'educació
    • Programa educatiu
    • Scale-Up! El joc empresarial
    • Visita Odoo
    Obtindre el programari
    • Descarregar
    • Comparar edicions
    • Novetats de les versions
    Col·laborar
    • GitHub
    • Fòrum
    • Esdeveniments
    • Traduccions
    • Converteix-te en partner
    • Services for Partners
    • Registra la teva empresa comptable
    Obtindre els serveis
    • Troba un partner
    • Troba un comptable
    • Contacta amb un expert
    • Serveis d'implementació
    • Referències del client
    • Suport
    • Actualitzacions
    Github Youtube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Programar una demo
  • Preus
  • Ajuda

Odoo is the world's easiest all-in-one management software.
It includes hundreds of business apps:

  • CRM
  • e-Commerce
  • Comptabilitat
  • Inventari
  • PoS
  • Projectes
  • MRP
All apps
You need to be registered to interact with the community.
All Posts People Badges
Etiquetes (View all)
odoo accounting v14 pos v15
About this forum
You need to be registered to interact with the community.
All Posts People Badges
Etiquetes (View all)
odoo accounting v14 pos v15
About this forum
Ajuda

How can I dynamically filter many2one fields in Odoo 17 models?

Subscriure's

Get notified when there's activity on this post

This question has been flagged
many2onedomain_filterdynamic filter
3 Respostes
3066 Vistes
Avatar
Bahrom Najmiddinov
class OrderPatient(models.Model):
_name = 'hms.order.patient'
_description = 'Order Patient'

order_id = fields.Many2one('hms.order', invisible=True, readonly=True)
service_id = fields.Many2one('hms.service', string="Service", domain='_onchange_service_id_domain')
doctor_id = fields.Many2one('hr.employee', string="Doctor")

# service_id_domain = fields.Char(compute='_compute_service_id_domain', store=False)
# doctor_id_domain = fields.Char(compute='_compute_doctor_id_domain', store=False)

@api.onchange('doctor_id')
def _onchange_doctor_id(self):
"""Update services and clear invalid service"""
if self.doctor_id:
allowed_services = self.doctor_id.service_ids
# Clear service if not valid for new doctor
if self.service_id not in allowed_services:
self.service_id = False
self.service_id_domain = [('id', 'in', allowed_services.ids)]
return {'domain': {'service_id': [('id', 'in', allowed_services.ids)]}}
else:
self.service_id = False
self.service_id_domain = []
return {'domain': {'service_id': []}}

@api.onchange('service_id')
def _onchange_service_id(self):
"""Update doctors and clear invalid doctor"""
if self.service_id:
allowed_doctors = self.env['hr.employee'].search(
[('service_ids', 'in', self.service_id.ids)]
)
# Clear doctor if not valid for new service
if self.doctor_id not in allowed_doctors:
self.doctor_id = False
self.doctor_id_domain = {'domain': {'doctor_id': [('id', 'in', allowed_doctors.ids)]}}
return {'domain': {'doctor_id': [('id', 'in', allowed_doctors.ids)]}}
else:
self.doctor_id = False
self.doctor_id_domain = {'domain': {'doctor_id': []}}
return {'domain': {'doctor_id': []}}


I want to achieve the following behavior:

  1. When a Doctor is selected, only the services that are allowed for that Doctor should be available for selection in the Service field. If the selected service is no longer valid for the Doctor, it should be cleared.
  2. When a Service is selected, only the Doctors that are allowed to perform that Service should be available for selection in the Doctor field. If the selected Doctor no longer provides the selected Service, it should be cleared.
0
Avatar
Descartar
Avatar
Cybrosys Techno Solutions Pvt.Ltd
Best Answer

Hi,

Please refer to the code below:


class OrderPatient(models.Model):

    _name = 'hms.order.patient'

    _description = 'Order Patient'


    order_id = fields.Many2one('hms.order', invisible=True, readonly=True)

    service_id = fields.Many2one(

        'hms.service',

        string="Service",

        domain="[('id', 'in', available_service_ids)]"

    )

    doctor_id = fields.Many2one(

        'hr.employee',

        string="Doctor",

        domain="[('id', 'in', available_doctor_ids)]"

    )

    available_service_ids = fields.Many2many(

        'hms.service', compute='_compute_available_service_ids', string="Available Services"

    )

    available_doctor_ids = fields.Many2many(

        'hr.employee', compute='_compute_available_doctor_ids', string="Available Doctors"

    )


    @api.depends('doctor_id')

    def _compute_available_service_ids(self):

        for record in self:

            if record.doctor_id:

                record.available_service_ids = record.doctor_id.service_ids

                if record.service_id and record.service_id not in record.available_service_ids:

                    record.service_id = False

            else:

                record.available_service_ids = self.env['hms.service'].browse([])

                record.service_id = False


    @api.depends('service_id')

    def _compute_available_doctor_ids(self):

        for record in self:

            if record.service_id:

                allowed_doctors = self.env['hr.employee'].search([

                    ('service_ids', 'in', record.service_id.id)

                ])

                record.available_doctor_ids = allowed_doctors

                if record.doctor_id and record.doctor_id not in record.available_doctor_ids:

                    record.doctor_id = False

            else:

                record.available_doctor_ids = self.env['hr.employee'].browse([])

                record.doctor_id = False


Hope it helps.

0
Avatar
Descartar
Avatar
Dino Varghese
Best Answer

Hi Bahrom Najmiddinov,

Returning a domain from the @api.onchange​  method is deprecated in Odoo 17. See the link below for the recommended alternative.
https://github.com/odoo/odoo/blob/26239b2d0bdbc2f06d50f7739d61c490248b65bb/addons/account/models/account_tax.py#L1633C5-L1633C154

1
Avatar
Descartar
Bahrom Najmiddinov
Autor

thanks

Avatar
D Enterprise
Best Answer

Hi,

please try this code 

from odoo import models, fields, api


class OrderPatient(models.Model):

    _name = 'hms.order.patient'

    _description = 'Order Patient'


    order_id = fields.Many2one('hms.order', invisible=True, readonly=True)

    service_id = fields.Many2one('hms.service', string="Service")

    doctor_id = fields.Many2one('hr.employee', string="Doctor")


    @api.onchange('doctor_id')

    def _onchange_doctor_id(self):

        """Filter services by selected doctor"""

        if self.doctor_id:

            allowed_services = self.doctor_id.service_ids

            if self.service_id not in allowed_services:

                self.service_id = False

            return {

                'domain': {

                    'service_id': [('id', 'in', allowed_services.ids)],

                }

            }

        else:

            self.service_id = False

            return {'domain': {'service_id': []}}


    @api.onchange('service_id')

    def _onchange_service_id(self):

        """Filter doctors by selected service"""

        if self.service_id:

            allowed_doctors = self.env['hr.employee'].search([

                ('service_ids', 'in', self.service_id.id )

            ])

            if self.doctor_id not in allowed_doctors:

                self.doctor_id = False

            return {

                'domain': {

                    'doctor_id': [('id', 'in', allowed_doctors.ids)],

                }

            }

        else:

            self.doctor_id = False

            return {'domain': {'doctor_id': []}}


i hope it is usefull

0
Avatar
Descartar
Enjoying the discussion? Don't just read, join in!

Create an account today to enjoy exclusive features and engage with our awesome community!

Registrar-se
Related Posts Respostes Vistes Activitat
Odoo 13 many2one filter base of the current user Solved
many2one list domain_filter
Avatar
Avatar
Avatar
2
de nov. 22
5351
Filter records in Many2One by records parents ID?
many2one domain_filter odoo12
Avatar
3
de nov. 20
4749
How to filter the domain of a selectbox depending on the value of another selectbox Solved
many2one domain_filter odoo11
Avatar
Avatar
1
de nov. 18
6439
Domain filter odoo11 manyToOne
many2one domain_filter odoo11
Avatar
5
de febr. 18
5438
How to give Domain filter for one2many field base on the condition of another field? (Odoo 13) Solved
many2one one2many onchange domain_filter
Avatar
Avatar
2
de jul. 22
12710
Community
  • Tutorials
  • Documentació
  • Fòrum
Codi obert
  • Descarregar
  • GitHub
  • Runbot
  • Traduccions
Serveis
  • Allotjament a Odoo.sh
  • Suport
  • Actualització
  • Desenvolupaments personalitzats
  • Educació
  • Troba un comptable
  • Troba un partner
  • Converteix-te en partner
Sobre nosaltres
  • La nostra empresa
  • Actius de marca
  • Contacta amb nosaltres
  • Llocs de treball
  • Esdeveniments
  • Pòdcast
  • Blog
  • Clients
  • Informació legal • Privacitat
  • Seguretat
الْعَرَبيّة 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 és un conjunt d'aplicacions empresarials de codi obert que cobreix totes les necessitats de la teva empresa: CRM, comerç electrònic, comptabilitat, inventari, punt de venda, gestió de projectes, etc.

La proposta única de valor d'Odoo és ser molt fàcil d'utilitzar i estar totalment integrat, ambdues alhora.

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