A Step-by-Step Guide
Firstly, the name search function odoo18 helps you link record lookups in Odoo 18 apps. Additionally, you can extend the default name_search method to include email, phone, and other fields. Moreover, you can make record search fast and clear by customizing name search function odoo18. Furthermore, this tutorial guides you step by step through each code piece and key setting.
Understanding the name_search Function in Odoo18
Firstly, Odoo 18 ships with a built-in name_search method that runs when you look up Many2one fields. Additionally, this method queries the name field by default and returns matching records. Moreover, the name_search method accepts parameters such as name, args, operator, and limit. Furthermore, you can use the operator argument to change the match type, such as ‘ilike’ for case-insensitive search. However, the default code only looks at the record name field. Therefore, you often need to add additional fields for better lookup. Hence, customizing the name_search method gives you more control over search logic. Meanwhile, the Odoo docs provide a basic reference for the name_search API. Also, you can find extra details in the Odoo 18 documentation on name_search.
Default Behavior of the name_search Function
Firstly, the default name_search method only searches the record name field. Additionally, it filters results using the operator you pass, such as ‘ilike’. Moreover, it merges the args parameter into the search domain without altering your filters. Furthermore, it limits the output to a set number of records, which you can adjust. However, the default code does not cover cases like email or phone lookup. Therefore, you need to override the method when you want those fields. Meanwhile, this override process runs in your custom module so that you do not touch core code. Also, this design keeps your changes safe when you update Odoo.
Function Signature and Parameters
Firstly, the name_search method signature looks like this:
@api.model
def name_search(self, name, args=None, operator='ilike', limit=100):
# default code here
return self._search(expression.AND([domain, args]), limit=limit)
Additionally, each parameter plays a key role in search logic. Moreover, the name argument holds the text to match, which you type into the search box. Furthermore, the args argument lets you add custom domain filters. However, the operator argument sets how Odoo checks for matches, such as ‘like’ or ‘ilike’. Therefore, you can tweak operator to match your needs. Meanwhile, the limit argument caps the number of records returned to avoid slow queries. Also, you can adjust limit to control the performance.
Why Customize name_search in Odoo 18?
Firstly, you can tailor search results to fit your business case. Additionally, you can include extra fields such as email, phone, or code. Moreover, you can speed up the search by limiting fields and adding indexes. Furthermore, you can improve user satisfaction by making the search smarter. However, you might face large data sets, which makes simple name lookup slow. Therefore, customizing name_search helps you add domains and filters to speed things up. Meanwhile, Odoo 18 offers hooks to override core logic, which you can use in your own module. Also, you can build a more dynamic search function without touching the core code.
Prerequisites for Custom name_search Function odoo18
Firstly, you need a local Odoo 18 development environment running on your machine. Additionally, you need basic Python skills to edit your module code. Moreover, you need access to the Odoo add-ons folder to add your custom module. Furthermore, you need a code editor like VS Code or PyCharm to manage your files. However, if you use Odoo.sh or a Docker setup, you can also follow along. Therefore, choose the environment that fits your workflow. Meanwhile, ensure you can restart Odoo and update modules quickly for testing. Also, check that you have user rights to install and upgrade modules.
Odoo 18 Setup
Firstly, you should install Odoo 18 on your local or remote server. Additionally, you can follow the official Odoo installation guide for your platform. Moreover, you can use a container to isolate dependencies. Furthermore, you can clone the Odoo repository from GitHub to get the latest code. However, ensure you match your Python version and dependencies. Therefore, verify your pip requirements file and install modules. Meanwhile, set up a PostgreSQL user and database for Odoo. Also, configure your Odoo config file to point to the database.
Python Basics
Firstly, you need to know how to create and extend Python classes. Additionally, you need to understand decorators like @api.model in Odoo. Moreover, you need to know how to work with lists and tuples in Python. Furthermore, you need basic knowledge of Python syntax to avoid errors. However, you do not need to be a Python pro to complete this tutorial. Therefore, follow each code snippet carefully. Meanwhile, test your code in small steps to ensure it works. Also, use print statements or logs to debug your code if needed.
Step-by-Step Guide to Build Custom name_search in Odoo18
Firstly, you will create a new module scaffold for your custom code. Additionally, you will define the module manifest and Python files. Moreover, you will inherit the res.partner model to extend its name_search method. Furthermore, you will implement the logic to search by name, email, and phone fields. However, you must test each step to catch errors early. Therefore, follow the detailed code and explanation below.
Creating a New Module
Firstly, open your add-ons folder in your Odoo installation. Additionally, create a new folder named partner_search_custom. Moreover, make sure the folder name has no spaces or special characters. Furthermore, create the following files inside that folder:
__init__.py__manifest__.pymodels/__init__.pymodels/res_partner.py
However, you can also use the Odoo scaffolding command, which speeds up this step. Therefore, run odoo-bin scaffold partner_search_custom . at your terminal. Meanwhile, check that the files appear in your folder. Also, open each file in your code editor.
Module Manifest File
Firstly, open __manifest__.py and add the basic module metadata. Additionally, set the module name, version, author, and dependencies. Moreover, include the Odoo base modules you plan to extend. Furthermore, define the license and category for the module. However, keep the manifest simple to avoid errors. Therefore, your manifest should look like this:
# __manifest__.py
{
'name': 'Partner Search Custom',
'version': '18.0.1.0.0',
'summary': 'Enhance partner search by email and phone',
'description': """
This module customizes the name_search function odoo18
for the res.partner model to include email and phone lookups.
""",
'author': 'Your Name',
'website': 'https://your-site.com',
'category': 'Tools',
'license': 'LGPL-3',
'depends': ['base', 'contacts'],
'data': [],
'installable': True,
'application': False,
}
Defining the Inherited Model
Firstly, open models/res_partner.py in your editor. Additionally, import the needed Odoo classes. Moreover, inherit res.partner to add your custom code. Furthermore, implement the name_search override. However, ensure you indent your code correctly. Therefore, include the following code:
# models/res_partner.py
from odoo import api, models
class ResPartner(models.Model):
_inherit = 'res.partner'
@api.model
def name_search(self, name='', args=None, operator='ilike', limit=100):
args = list(args or [])
# If no search term, use default behavior
if not name:
return super(ResPartner, self).name_search(
name=name, args=args, operator=operator, limit=limit
)
# Build a custom domain
domain = ['|', '|',
('name', operator, name),
('email', operator, name),
('phone', operator, name)]
# Add extra filters if provided
if args:
domain = ['&'] + args + domain
# Search and fetch only display_name field
partners = self.search_fetch(
domain, ['display_name'], limit=limit
)
# Return in the format Odoo expects
return [(partner.id, partner.display_name) for partner in partners]
Code Explanation
Firstly, we convert args into a list so that we can modify it easily. Additionally, we check if the name argument is empty to avoid overriding default behavior unnecessarily. Moreover, we build a domain that uses the operator argument to search the name, email, and phone fields. Furthermore, we combine this domain with any extra filters passed in args. However, we only fetch the display_name field to avoid loading full records into memory. Therefore, we use search_fetch to speed up the query. Meanwhile, we map the search results to a list of tuples (id, display_name) which is the format Odoo expects. Also, we return that list so that the Many2one widget shows the right options.
Advanced Tips for name_search Optimization in Odoo18
Firstly, you can add an index to fields such as email and phone in PostgreSQL to speed up queries. Additionally, you can use computed fields to store combined search keys. Moreover, you can override the name_get method to alter how records display in the result list. Furthermore, you can set up caching to store frequent queries for repeated use. However, keep an eye on cache invalidation to avoid stale results. Therefore, test performance with real data before and after changes. Meanwhile, use Odoo’s developer tools to profile your code. Also, document any custom logic so that your team can maintain it.
Limiting Results
Firstly, you can adjust the limit argument in your code to fetch fewer records. Additionally, you can make the limit configurable via module settings. Moreover, you can stop searching after the first match in certain cases. Furthermore, you can show a “load more” link in your UI to fetch extra results when users need them. However, you need to handle the domain correctly to avoid duplicate records. Therefore, test each scenario to ensure that limit works as expected. Meanwhile, log warnings when limit values go beyond safe thresholds. Also, explain the purpose of the limit in your code comments.
Caching and Performance
Firstly, you can cache the search domain results in memory to speed up repeated queries. Additionally, you can use Python’s @lru_cache decorator to cache method calls at the server level. Moreover, you can store computed search keys in a stored field so that the database can index them. Furthermore, you can push heavy search logic into SQL views for faster execution. However, complex SQL views may be harder to maintain. Therefore, weigh the benefit of speed against the cost of complexity. Meanwhile, monitor your server performance while you test your code. Also, remove any redundant queries that may slow down your system.
Security and Protection
Firstly, you must avoid SQL injection by letting Odoo’s ORM handle domain filters. Additionally, you should sanitize any user input if you use raw SQL queries. Moreover, you can restrict search logic to certain user groups to enforce data privacy. Furthermore, you can add record rules to limit which records appear in the search results. However, strong rules may slow down the search. Therefore, test the interplay between performance and security. Meanwhile, update your access control lists when you add new fields. Also, document your security settings in your module readme.
Testing the Custom name_search Implementation
Firstly, you should write unit tests that call the name_search method directly. Additionally, you should test edge cases such as empty search terms and unusual characters. Moreover, you should test with real partner data to simulate production. Furthermore, you should run these tests automatically as part of your CI pipeline. However, manual tests also help you catch UI-level issues. Therefore, use Odoo’s built-in test framework to write your tests. Meanwhile, you can add debug logs to see how your domain builds. Also, after each change, run your tests to make sure nothing breaks.
Writing Unit Tests
Firstly, create a test file in your module under tests/test_res_partner.py. Additionally, import the TransactionCase class from Odoo test framework. Moreover, write methods that set up sample partner records with names, emails, and phones. Furthermore, call:
results = self.env[‘res.partner’].name_search(‘john’, [], ‘ilike’, 10)
However, you need to assert that the result returns only partners that match. Therefore, use self.assertIn and self.assertEqual to check your values. Meanwhile, run Odoo with the --test-enable flag to include your tests. Also, consider using @tagged('post_install', '-at_install') to skip tests at install time.
Running Tests
Firstly, open a terminal in your Odoo root directory. Additionally, execute:
odoo-bin --addons-path addons,partner_search_custom -d test_db --test-enable --stop-after-init
Moreover, watch the output to see which tests pass or fail. Furthermore, fix any errors or assertion failures that you find. However, you may need to drop and recreate the test database after major changes. Therefore, use a separate test database to isolate your tests from production. Meanwhile, you can use pytest if you prefer. Also, document any test commands in your README file.
Common Pitfalls and Solutions
Firstly, you might forget to convert args to a list, which causes errors. Additionally, you might use incorrect operators like ‘like’ when you need ‘ilike’. Moreover, you might return the wrong format and break the Many2one widget. Furthermore, you might create recursive calls if you call super incorrectly. However, you can avoid these issues by following the structure shown above. Therefore, debug each step and test often. Meanwhile, use Odoo logs to trace errors in your code. Also, ask for help in the Odoo community if you get stuck.
Handling Empty Search Terms
Firstly, you need to check if name is empty at the start of your method. Additionally, you need to call super() to keep default behavior. Moreover, you can skip building domains to save CPU cycles. Furthermore, you can return an empty list if you want no results. However, returning an empty list may confuse users. Therefore, choose the behavior that fits your use case. Meanwhile, document this behavior in your code. Also, use logs to show your choice during debugging.
Dealing with Large Data Sets
Firstly, you need to add database indexes to fields you search often. Additionally, you can use PostgreSQL explain plans to inspect slow queries. Moreover, you can limit results and add pagination or “load more” UI patterns. Furthermore, you can add search filters on the client side to reduce server load. However, heavy filters may add complexity. Therefore, balance user experience against performance. Meanwhile, you can batch queries in Python if needed. Also, regularly vacuum your database to keep it fast.
Ensuring Search Indexes
Firstly, check if your email and phone fields have indexes by running \d res_partner in psql. Additionally, you can add indexes in a migration script using SQL or Odoo’s index=True. Moreover, you can mark computed fields as stored to let Odoo index them. Furthermore, you can use the _sql_constraints attribute in your model to define constraints and indexes. However, too many indexes can slow down writes. Therefore, only index fields you search on often. Meanwhile, monitor your database performance with tools like pgAdmin. Also, schedule database maintenance tasks for best results.
FAQs About name_search function odoo18
Can I search on computed fields?
Firstly, you can search on computed fields if you mark them as stored. Additionally, you need to add store=True in your field definition. Moreover, Odoo will then create an index on that field if you set index=True. Furthermore, you can use the computed field in your domain inside name_search. However, computed fields may need an @api.depends decorator to update correctly. Therefore, test your computed fields before you add them to domains. Meanwhile, document the computation logic to avoid confusion. Also, check performance after you add more fields.
What happens if I set limit to 0?
Firstly, Odoo interprets limit=0 as no limit, which may return all matching records. Additionally, this can lead to slow queries and UI slowdowns. Moreover, you can use this approach only if you have very few records. Furthermore, you can add client-side pagination to handle large result sets. However, you should avoid unbounded queries in production. Therefore, set a safe default limit like 100 or 200. Meanwhile, document the limit behavior in your code. Also, log warnings if you detect that limit is too high.
How to add multi-language support?
Firstly, Odoo supports multi-language fields out of the box with translate=True. Additionally, you can search on translated fields by adding ('name', operator, name) for each language variant. Moreover, you need to ensure that you pass the lang context for specific users. Furthermore, you can use the @api.model decorator with appropriate context keys to handle multi-language logic. However, you may need to rebuild translations if you change field names. Therefore, test your search logic under different language contexts. Meanwhile, enable i18n in your module manifest. Also, add translation keys in your XML files.
Conclusion
Firstly, the name search function odoo18 tutorial showed you how to enhance search in Odoo 18 by customizing the name_search method. Additionally, you saw how to set up a module, inherit a model, and write the custom code. Moreover, you learned about advanced tips like indexing, caching, and security. Furthermore, you explored how to test your code, handle edge cases, and scale for large data sets. However, you still need to adapt the example to your own needs. Therefore, feel free to expand the code to include other fields like VAT, mobile, or reference. Meanwhile, share your feedback in the comments or report issues on your module repository. Also, keep an eye on the Odoo 18 Documentation for more updates.
Happy coding!
Discover more from teguhteja.id
Subscribe to get the latest posts sent to your email.

