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

(ODOO 10 How To) Compute domain / Dynamic Domain / set a domain based on a function or a field

Subscriure's

Get notified when there's activity on this post

This question has been flagged
domaindomain_filtercomputedomainsdymanic_fields
2 Respostes
23733 Vistes
Avatar
Régis Pirard

After many attemps and reading a lot here, I was finally able to set the domain of a field dynamically using a function.

I will post my findings here in case it would help anyone.


1) Domain is typically set in XML view like this : 

domain="[('id', 'in', ['1','2','3','4','5'])]"

Here, I provide five ID's manually for the example.


2) Another method to set the same domain is to write a function in your model .py

Example to modify domain depending on "yourfield" :


@api.onchange("yourfield")

def _onchange_all_partner_ids(self):
    res = {}
    res['domain'] = {'partner_id': [('id', '=',   ['1','2','3','4','5'] )], } 
    return res


3) Another method to provide ID's dynamicaly with a function, we can use à "virtual non-stored and computed" many2many field and use it in the view: 

In .py file :

#first function retrieves a list of ID's :

@api.multi
def _get_all_partner_ids(self):
     partner_id_list = [] 

# write some code to retrieve partners in xxxx

     partner_id_list.append( xxxxx.id ) 
     return partner_id_list


#second function is a compute for field all_partner_ids   : 

@api.multi
@api.depends("partner_contact_id")
def _load_all_partner_ids(self):
     self.all_partner_ids = [(6,0, self._get_all_partner_ids())]

​

#last : define all_partner_ids many2many field

all_partner_ids = fields.Many2many('res.partner',string="All partners",compute="_load_all_partner_ids") 


in .XML

In your form view, you have to add you many2many field like this :

<field name="all_partner_ids" invisible="True"/>


And you finally set domain like this : 

domain="[('id', 'in', all_partner_ids and all_partner_ids[0] and all_partner_ids[0][2] or False)]"



To give a more specific example : 

I wanted to set a domain on field "partner_id" based on a list of parner ID that I would compute in a function.

That list had to be retrieved recursively based on another field : partner_contact_id.


I had to do two things : 

A) I began to set domain with "on_change("partner_contact_id)" compute domain, like this : 

@api.multi
def _get_all_partner_ids(self):
     if not self.partner_contact_id.id:
          partner_id_list = []
     else: 
          partner_id_list = []
          partner_id_obj = self.env['res.partner'].search([('parent_id', '=', self.partner_contact_id.id)])
          for data in partner_id_obj:
               partner_id_list.append(data.id)
               for ids in partner_id_list:
                    childs = self.env['res.partner'].search([('parent_id', '=', ids)])
                         for child in childs:
                         if child.id <> self.partner_contact_id.id and child.id not in partner_id_list:
                              partner_id_list.append(child.id)
     return partner_id_list


@api.onchange("partner_contact_id")
def _onchange_all_partner_ids(self):
     if not self._get_all_partner_ids():
          res = {}
          res['domain'] = {'partner_id': [],
                                    'partner_invoice_id': [],
                                    'partner_shipping_id': []
                                   }
          return res
     else:
          res = {}
          res['domain'] = {'partner_id': [('id', '=', self._get_all_partner_ids())],
     'partner_invoice_id': [('id', '=', self._get_all_partner_ids())],
     'partner_shipping_id': [('id', '=', self._get_all_partner_ids())]
     }
     return res


But when I loaded an old sale order, or when I created a new one, " @api.onchange("partner_contact_id") " was not triggered and my domain was not set.


B)   To solve this, I decided to compute a many2many field with my ID list :

in .py :

@api.multi
@api.depends("partner_contact_id")
def _load_all_partner_ids(self):
     self.all_partner_ids = [(6,0, self._get_all_partner_ids())]

all_partner_ids = fields.Many2many('res.partner',string="All partners",compute="_load_all_partner_ids")


in xml :

<field name="all_partner_ids" invisible="True"/>

<field name="partner_id" position="attributes">
<attribute name="domain">[('id', 'in', all_partner_ids and all_partner_ids[0] and all_partner_ids[0][2] or False)]</attribute>
</field>

4
Avatar
Descartar
Gabriel

Hi men, i was looking for a solution like that for some days right now.

REALLY THANK FOR THE GREAT EXPLATION YOU GIVE!

Régis Pirard
Autor

Thanks for your feedback ! You're welcome !

Sehrish

idea: https://learnopenerp.blogspot.com/2021/03/domain-filter-one2many-child-fields-on-the-basis-of-parent-fields.html

Sehrish

https://learnopenerp.blogspot.com/2018/12/add-domain-on-many2many-field-in-odoo.html

Avatar
Niyas Raphy (Walnut Software Solutions)
Best Answer

Hi,

Other than this method, you can use the web domain field module from oca for the same:  Web Domain Field


See this: Return Dynamic Domain For Field In Odoo


How to use:

.. code-block:: xml

<field name="product_id_domain" invisible="1"/>
<field name="product_id" domain="product_id_domain"/>


.. code-block:: python

product_id_domain = fields.Char(
compute="_compute_product_id_domain",
readonly=True,
store=False,
)

@api.multi
@api.depends('name')
def _compute_product_id_domain(self):
for rec in self:
rec.product_id_domain = json.dumps(
[('type', '=', 'product'), ('name', 'like', rec.name)]
)

Returning domain from the onchange function: How To Give Domain For A Field Based On Another Field

Thanks

4
Avatar
Descartar
Avatar
Dries Cox
Best Answer

Hello, Thank you for your extended explanation! great work.

I have been trying your method to filter sale order lines based on the field value of a field in the order-line, but it looks like this method doesn't filters One2many fields?

When I follow your method everything works up until the filtering of the m2m field. I made it visible on my view and could see that it behaved perfectly like I wanted. So filtering the lines each time on update of the parent field.

Do you know if this solution is possible to filter a O2m field? Or do you know how to do this some other way.

Thanks

0
Avatar
Descartar
Niyas Raphy (Walnut Software Solutions)

See my answer about the web domain field module

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
how to set multiple conditions in search method in odoo9
domain search domain_filter domains
Avatar
Avatar
1
de des. 16
18150
DBFilter www or domain Solved
domain db_filter domain_filter domains dbfilter
Avatar
Avatar
2
de maig 17
9769
Many2one Domain (Filter by user security groups)
security domain many2one domain_filter domains
Avatar
0
d’ag. 16
4991
Condition Drop Down Items
domain domain_filter
Avatar
0
de febr. 25
18
Add my own domain via NameCheap in Odoo
domain domains
Avatar
Avatar
2
de des. 20
6426
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