Difference Between browse() and search() in Odoo
✅ Purpose of Each
Method | Purpose |
browse() | Fetch records by known IDs without querying the database immediately. |
search() | Find records based on domain filters, performs a real database query. |
📌 Realistic Odoo Examples
1. browse() – When you already know the record ID(s)
product = self.env['product.product'].browse(25)
- Fetches product with ID 25.
- If record with ID 25 does not exist, it returns an empty recordset (not error).
- No SQL query is executed until the record is actually accessed (lazy loading).
🧪 Example in Context:
def get_product_name(self, product_id):
product = self.env['product.product'].browse(product_id)
return product.name if product.exists() else 'Unknown'
2. search() – When you need to find records based on criteria
- Returns all products with type = 'product'.
- Performs actual SQL query immediately.
- Returns an empty recordset if no records match.
products = self.env['product.product'].search([('type', '=', 'product')])
🧪 Example in Context:
def get_all_storable_products(self):
products = self.env['product.product'].search([('type', '=', 'product')])
return products
🧠 Key Differences
Feature | browse() | search() |
Input | Record ID(s) only | Domain (list of filter conditions) |
Query Execution | Lazy (on access) | Immediate database query |
Returns | Recordset (even if empty) | Recordset (even if empty) |
Typical Use Case | Access known records (e.g., from foreign keys, ID) | Search using conditions or filters |
Error on Non-existent ID | No, returns empty recordset | No error; just returns empty result |
✅ Summary Table
Method | Used For | Performs DB Query? | Accepts Domain? | Accepts IDs? |
browse() | Accessing known records | ❌ (Lazy access) | ❌ | ✅ |
search() | Finding records by criteria | ✅ (Immediate) | ✅ | ❌ |