Efficient data retrieval is the cornerstone of any robust Enterprise Resource Planning (ERP) system. In Odoo 18, the ability to quickly locate specific records dramatically enhances user productivity and overall system usability. While Odoo’s default search mechanisms are functional, there often comes a point where out-of-the-box capabilities fall short of specific business needs. This is where the power of Odoo name_search customize comes into play.
This comprehensive guide, inspired by insightful discussions from Odoo functional consultants like Arsalan Yasin (though a direct video link was not provided in the context), will walk you through the process of customizing Odoo’s name_search function. By the end, you’ll be equipped to enable multi-field searching, allowing your users to find records by email, phone number, or any other relevant attribute, thereby drastically improving user experience and data accessibility.
The Critical Need to Odoo name_search customize
Odoo offers powerful relational fields, such as Many2one, that facilitate seamless connections between different models. When users interact with these fields, say, when linking a sales order to a customer, an efficient search mechanism for existing records is absolutely essential. By default, Odoo primarily searches records based on their name field. While this works for basic scenarios, real-world business operations often demand more flexibility.
Imagine a scenario where your sales team needs to quickly find a contact, but they only remember the customer’s email address or phone number, not their exact company name. With the default name_search behavior, they would be out of luck, forced to navigate to the Contacts app, perform a separate search, and then return to their task. This inefficiency can lead to wasted time, frustration, and a dip in productivity.
Customizing the name_search function addresses these limitations directly. By implementing your own logic, you can:
- Enhance User Experience (UX): Allow users to search using a broader range of criteria, mimicking how they naturally recall information.
- Accelerate Data Retrieval: Reduce the steps required to find a record, making the system feel faster and more intuitive.
- Improve Data Accuracy: Minimize the chances of creating duplicate records because users can’t find existing ones.
- Boost Productivity: Empower users to complete tasks more quickly and with less friction.
This ability to Odoo name_search customize is not just a technical tweak; it’s a strategic enhancement that can significantly impact your business’s operational efficiency.
Decoding Odoo’s name_search Function
Before we dive into implementation, it’s vital to understand what the name_search function is and how it operates within Odoo.
The name_search function is a core method within Odoo’s ORM (Object-Relational Mapping) that allows users to search for records based on partial matches or by fields beyond just the default name field. It’s automatically called by Odoo whenever a user types into a Many2one field or other relational input widgets.
Default Function Structure
The basic structure of the name_search function is as follows:
@api.model
def name_search(self, name='', args=None, operator='ilike', limit=100):
# Custom implementation or default logic
# The default behavior typically searches the 'name' field
return super().name_search(name=name, args=args, operator=operator, limit=limit)
Let’s break down its parameters:
self: The instance of the model on which thename_searchis called.name(str): This is the actual search term entered by the user in the Many2one field. If the user types “John Doe,”namewill be “John Doe.”args(list): An optional list of additional domain filters. This parameter allows other parts of Odoo (or even your custom code) to pass extra criteria to refine the search. For example, you might want to only search for active partners, soargscould be[('active', '=', True)].operator(str): Defines how thenamesearch term should be matched against the fields. Common operators include:'ilike': Case-insensitive partial match (e.g., “john” matches “John Doe”). This is the most frequently used operator forname_search.'like': Case-sensitive partial match.'=': Exact match.
limit(int): The maximum number of records Odoo should return. By default, it’s often 100, preventing overwhelming the user with too many results.
Understanding these parameters is the first step towards effectively being able to Odoo name_search customize.
Step-by-Step Guide to Odoo name_search customize in Odoo 18
Let’s dive into a practical example. We will customize the name_search function for the res.partner model (Odoo’s contact model), allowing users to search not only by name but also by email and phone number.
3.1 Prerequisites for Customization
Before you start coding, ensure you have:
- Basic Odoo Development Knowledge: Familiarity with Odoo’s module structure, Python, and XML.
- A Custom Odoo Module: All customizations should reside within a custom module to ensure upgradeability and proper management. If you don’t have one, create a basic module following Odoo’s developer documentation. You can find general Odoo development documentation at Odoo’s Official Documentation.
3.2 Inheriting the Target Model: res.partner
To modify the name_search behavior of res.partner, you need to inherit this model within your custom module. Create a new Python file (e.g., models/res_partner.py) inside your custom module’s models directory and add the initial inheritance code:
# my_custom_module/models/res_partner.py
from odoo import api, models
class ResPartner(models.Model):
_inherit = 'res.partner'
# Your custom name_search function will go here
The _inherit = 'res.partner' line is crucial as it tells Odoo that your ResPartner class is extending the existing res.partner model, allowing you to override or add methods to it.
3.3 Crafting Your Custom name_search Logic
Now, let’s implement the core logic to Odoo name_search customize for multi-field searching. Place the following code within your ResPartner class in my_custom_module/models/res_partner.py:
# my_custom_module/models/res_partner.py
from odoo import api, models
from odoo.osv import expression
class ResPartner(models.Model):
_inherit = 'res.partner'
@api.model
def name_search(self, name='', args=None, operator='ilike', limit=100):
# 1. Ensure args is a mutable list to safely add/modify domain parts
args = list(args or [])
# 2. If no search term is provided, fall back to the default behavior
# This is crucial for cases where the user hasn't typed anything yet.
if not name:
return super(ResPartner, self).name_search(name=name, args=args, operator=operator, limit=limit)
# 3. Define the custom search domain for multiple fields
# We want to search by name OR email OR phone number.
domain = [
'|', '|',
('name', operator, name),
('email', operator, name),
('phone', operator, name),
('mobile', operator, name), # Adding mobile for even broader search
]
# 4. Combine with additional search arguments if any were passed
# The 'expression.AND()' method is a robust way to combine domains.
# This ensures that any 'args' are combined with our custom domain using a logical AND.
full_domain = expression.AND([args, domain])
# 5. Perform the search and retrieve results
# We use _search directly for efficiency, fetching IDs.
# The name_search function expects a list of (id, display_name) tuples.
partners = self.search(full_domain, limit=limit)
# 6. Format the result as a list of (id, display_name) tuples
return [(partner.id, partner.display_name) for partner in partners]
Code Explanation:
args = list(args or []): This line safely initializesargsas a mutable list. IfargsisNone(which it often is when no extra filters are provided), it creates an empty list. This prevents errors when we later try to combine domains.if not name: return super(ResPartner, self).name_search(...): This is a critical fallback. If the user hasn’t typed anything into the search box (nameis empty), we delegate the call to the parent class’sname_search. This ensures that the default behavior (e.g., showing recently used records) is preserved when no specific search term is entered. Thesuper()function is a powerful tool in Python for calling methods of a parent class. More onsuper()can be found in the Python documentation.domain = [...]: This is where the multi-field search magic happens.- The
'|'(OR operator) is used to combine multiple conditions. In['|', A, B], it means “A OR B”. For['|', '|', A, B, C], it means “A OR B OR C”. - We define conditions to search the
name,email,phone, andmobilefields using the providedoperator(typically'ilike') and the user’snamesearch term.
- The
full_domain = expression.AND([args, domain]): Here, we robustly combine anyargspassed to thename_searchfunction with our newly constructeddomain. Theexpression.AND()function fromodoo.osv.expressionis the recommended way to logically AND multiple Odoo domains. This ensures that if Odoo (or another module) adds a filter (e.g.,('is_company', '=', True)), it will correctly combine with our custom multi-field search.partners = self.search(full_domain, limit=limit): We use the standardself.search()method to query the database. This fetches the actual Odoo records (browse records) that match ourfull_domainand respects thelimit. The draft post suggested_searchwhich returns IDs, butself.search()which returns browse records, followed by extracting ID and display_name, is generally more readable and straightforward for the required return format.return [(partner.id, partner.display_name) for partner in partners]: Thename_searchfunction must return a list of tuples, where each tuple contains(record_id, record_display_name). This list comprehension efficiently converts the fetchedpartnersbrowse records into the required format.
3.4 Integrating Your Customization: __manifest__.py
For Odoo to recognize your new Python file and its customizations, you must include it in your module’s manifest file (__manifest__.py).
# my_custom_module/__manifest__.py
{
'name': 'My Custom Odoo Search Enhancements',
'version': '1.0',
'category': 'Extra Tools',
'summary': 'Enhances name_search functionality for improved record retrieval.',
'depends': ['base'], # Ensure 'base' is in dependencies as res.partner is in base
'data': [
# ... other data files if any ...
],
'demo': [],
'installable': True,
'application': False,
'auto_install': False,
'license': 'LGPL-3',
'post_init_hook': '_post_init_hook', # Example, often not needed for simple changes
'python_dependencies': [], # Example
'assets': {}, # Example
'sequence': 10, # Example
'external_dependencies': {}, # Example
'description': """
This module provides custom name_search functionality for Odoo models.
It enhances record search capabilities by allowing users to search
across multiple fields like email, phone, and name for res.partner.
""",
'author': 'Your Name/Company',
'website': 'https://www.yourwebsite.com',
'qweb': [], # Deprecated in Odoo 15, use 'assets'
}
Wait, I need to add the python file to the data or data equivalent section. data is for XML files. Python files for model definitions go into __init__.py and are loaded by the Python interpreter. The __manifest__.py handles module dependencies and which files belong to the module, but Python files are loaded via __init__.py structure.
Corrected __init__.py and __manifest__.py:
my_custom_module/__init__.py:# my_custom_module/__init__.py from . import modelsmy_custom_module/models/__init__.py:# my_custom_module/models/__init__.py from . import res_partnermy_custom_module/__manifest__.py: (No change needed here for Python files specifically, just ensuringbasedependency is there).{ 'name': 'My Custom Odoo Search Enhancements', 'version': '1.0', 'category': 'Extra Tools', 'summary': 'Enhances name_search functionality for improved record retrieval.', 'depends': ['base'], # 'base' module contains res.partner 'installable': True, 'application': False, 'auto_install': False, 'license': 'LGPL-3', 'description': """ This module provides custom name_search functionality for Odoo models. It enhances record search capabilities by allowing users to search across multiple fields like email, phone, and name for res.partner. """, 'author': 'Your Name/Company', 'website': 'https://www.yourwebsite.com', }This correction is important for Odoo development best practices regarding Python file loading.
3.5 Deploying Your Changes: Install/Upgrade Module
After making these code changes:
- Restart your Odoo server. This is essential for Odoo to recognize any changes made to Python files.
- Update your custom module.
- Navigate to the “Apps” module in your Odoo instance.
- Ensure “Developer mode” is activated (Settings > General Settings > Developer Tools).
- Search for your custom module (e.g., “My Custom Odoo Search Enhancements”).
- Click the “Upgrade” button. If it’s a new module, install it.
Testing Your Customized name_search Functionality
Now comes the exciting part: testing!
- Go to the Contacts app in your Odoo instance.
- Create a new contact if you don’t have one with distinct email and phone numbers. For example:
- Name:** “Alice Smith”
- **Email:** “alice.smith@example.com”
- **Phone:** “123-456-7890”
- Mobile:** “987-654-3210”
- Navigate to any Many2one field that links to
res.partner(e.g., on a Sales Order, Project Task, or even within the Contacts app when creating a new contact and linking to a ‘Company’). - Try searching using different criteria:
- Type “Alice” – it should find “Alice Smith”.
- Type “alice.smith@example.com” – it should find “Alice Smith”.
- Type “456-7890” (a part of the phone number) – it should find “Alice Smith”.
- Type “987-654” (a part of the mobile number) – it should find “Alice Smith”.
If your name_search function is correctly implemented, all these searches should successfully retrieve the “Alice Smith” contact. This immediate feedback demonstrates the power of being able to Odoo name_search customize.
Advanced Strategies and Best Practices for Odoo name_search Customization
While the example above provides a solid foundation, mastering Odoo name_search customize involves considering more advanced scenarios and adhering to best practices.
5.1 Performance Optimization
For large datasets, an inefficient name_search can severely impact performance.
- Index Fields:** Ensure that the fields you frequently search (like
email,phone,mobile) are indexed in your PostgreSQL database. Odoo often indexesnamefields by default, but custom fields or other frequently searched fields might need explicit indexing. This can be done by addingindex=Trueto your field definition in Python. - **Limit Results:** Always respect the
limitparameter. Returning an excessive number of records can strain both the database and the network. - Efficient Domain Construction:** Keep your search domains as simple and direct as possible. Avoid complex subqueries if a simpler approach yields the same result.
5.2 Security and Access Rights
The _search and search methods in Odoo inherently respect user access rights. When performing Odoo name_search customize, ensure that your custom logic doesn’t inadvertently expose records that a user shouldn’t see. The default self.search() call handles access rights automatically based on the current user.
5.3 Handling Complex Search Scenarios
You might need to search fields on related models or combine more intricate logic.
- Searching Related Models:** If you need to search a contact by the name of their company, you can do so using dot notation in your domain:
('company_id.name', operator, name). - **Combining More Fields:** Simply extend your
domainlist with more'|'operators and field conditions. For instance, to search by VAT number:domain = [ '|', '|', '|', '|', ('name', operator, name), ('email', operator, name), ('phone', operator, name), ('mobile', operator, name), ('vat', operator, name), # Search by VAT number ]
5.4 Maintainability and Documentation
- Clear Comments:** Document your custom
name_searchfunction thoroughly. Explain the purpose of each section of the code, especially the domain logic. - **Follow Odoo Standards:** Adhere to Odoo’s coding guidelines for variable naming, indentation, and structure.
5.5 Common Pitfalls and Troubleshooting
- Forgetting to Restart/Upgrade:** This is the most common mistake. Always restart your Odoo server and upgrade your module after Python code changes.
- **Incorrect Domain Syntax:** A misplaced
'|','&', or an incorrectly formatted tuple in your domain can lead to errors or unexpected search results. Useexpression.ANDandexpression.ORfor complex combinations to minimize syntax errors. - Field Not Found Errors:** Double-check field names (e.g.,
phonevs.partner_phone). - Debugging:** Use Odoo’s logging mechanism (
_logger.info("Debug message")) or a debugger to trace the execution of yourname_searchfunction and inspect thename,args, anddomainvariables.
Unleashing the Full Potential of Odoo with Tailored Search
The ability to Odoo name_search customize is a powerful tool in any Odoo developer’s arsenal. It moves beyond generic search functionality to provide a truly tailored experience that aligns with how your users think and operate. By implementing multi-field searches, you unlock several benefits:
- Empowered Users:** Your team can work more efficiently, reducing manual lookups and context switching.
- **Scalability:** As your database grows, an optimized
name_searchensures that performance doesn’t degrade, even with thousands or millions of records. - Business Agility:** You can quickly adapt Odoo to new business processes that require searching specific fields, without waiting for core Odoo updates.
This level of customization transforms Odoo from a generic ERP into a system that feels truly bespoke to your organization’s needs.
Conclusion
The name_search function in Odoo 18 offers an exceptional way to customize how records are retrieved through relational fields. By extending this function, you significantly enhance the user experience by enabling searches across multiple relevant fields like email, phone number, and more.
Implementing a custom name_search is particularly valuable when dealing with large datasets, ensuring that users can quickly find the precise information they need without hassle. By following the detailed, step-by-step approach outlined in this blog post, you can effectively Odoo name_search customize the search behavior in your Odoo applications to meet your specific business requirements, leading to a more intuitive, efficient, and user-friendly ERP system. Start tailoring your Odoo search experience today and witness the immediate impact on productivity!
Discover more from teguhteja.id
Subscribe to get the latest posts sent to your email.

