🔎 Deep Dive: search_fetch() in the Odoo ORM ⚡ As Odoo developers we often use .search() plus .read() or rely on fields loading on demand. When performance is critical, though, search_fetch() is a cleaner option — it reduces round-trips and loads exactly what you need. 🧠 What search_fetch() does Model.search_fetch(domain, field_names[, offset=0][, limit=None][, order=None]) • Runs a domain search • Retrieves the specified fields in a single step • Prevents additional SQL caused by lazy field access • Keeps results cached for better performance Think of it as a faster, single-query alternative to .search() followed by .read(). 💡 When it’s the right tool Reach for search_fetch() when: • ⚡ You need lower latency — e.g., API responses, dashboards, or server-side routines • 📉 You want to cut down on SQL queries • 📋 You only need a subset of fields (read-only) • 🛑 You don’t plan to alter the returned records 🧪 Example products = self.env['product.template'].search_fetch( domain=[('sale_ok', '=', True)], field_names=['name', 'list_price', 'currency_id'], limit=50, order='name ASC' ) This pulls 50 saleable products and preloads the requested fields in one efficient call. ⚠️ Quick caveats • Returns a standard recordset. • The listed fields are fully loaded into memory (no later lazy fetches). • Will raise AccessError if the user lacks read permission for the model/fields. 🛠️ Good scenarios to adopt it • REST or JSON endpoints • Reporting and analytics code • Custom dashboard backends • Any flow that’s read-heavy and sensitive to DB round-trips 💬 Have you tried search_fetch() in your Odoo apps? Drop your tips or experiences — let’s swap notes and optimize together!
How to use search_fetch() for better Odoo ORM performance
More Relevant Posts
-
🚀 Odoo Tips & Tricks: Understanding search_fetch() vs search() ⚙️ If you’re an Odoo developer or technical consultant, you’ve probably used the classic search() method countless times. But starting from Odoo 17, there’s a newer, more efficient method — search_fetch() — designed to optimize performance when fetching records. Let’s break it down 👇 🔍 search() Returns recordsets (full ORM objects). Loads all computed fields, relational data, and triggers ORM caching. Suitable when you need to manipulate records, call methods, or write data. Example: partners = self.env['res.partner'].search([('country_id', '=', 110)]) ⚡ search_fetch() Returns raw dictionary data instead of recordsets. Fetches only the fields you specify, improving speed and memory efficiency. Ideal for read-only data — like reports, dashboards, or API responses. Example: partners = self.env['res.partner'].search_fetch( [('country_id', '=', 110)], ['id', 'name', 'email'] ) 💡 When to Use What? ✅ Use search() → When you need ORM features or to modify records. ⚙️ Use search_fetch() → When you just need to read and display data fast. In short, search_fetch() is a performance-oriented alternative to search() — perfect for high-speed queries and lightweight data retrieval in modern Odoo versions. 🚀 #Odoo #OdooDevelopment #Odoo17 #Odoo18 #OdooTips #OdooPerformance #OdooDeveloper #ORM #search_fetch
To view or add a comment, sign in
-
Clean REST API in Odoo: How I Build Secure & Scalable Endpoints While Odoo traditionally uses JSON-RPC, modern integrations often require REST API endpoints—especially for mobile apps, external platforms, or microservices. Here’s how I built a clean, secure REST API in Odoo using controllers 👇 🛠 Sample REST Endpoint (Controller-Based) from odoo import http from odoo.http import request, Response import json class OrderAPIController(http.Controller): @http.route('/api/orders', type='json', auth='api_key', methods=['GET'], csrf=False) def get_orders(self, **kwargs): orders = request.env['sale.order'].sudo().search_read( [], ['name', 'partner_id', 'amount_total', 'state'] ) return {"status": "success", "data": orders} @http.route('/api/order/create', type='json', auth='api_key', methods=['POST'], csrf=False) def create_order(self, **data): try: order = request.env['sale.order'].sudo().create({ 'partner_id': data.get('partner_id'), 'date_order': data.get('date_order'), }) return {"status": "created", "order_id": order.id} except Exception as e: return Response(json.dumps({"error": str(e)}), status=400, mimetype='application/json') ✅ Best Practices I Follow ✔ Use auth='api_key' or OAuth—never auth='public' for sensitive data ✔ Use POST for create/update, GET for retrieving data ✔ Filter fields with search_read to avoid large payloads ✔ Always wrap responses in JSON format (status + data/error) ✔ Log failed API calls for debugging & auditing 🚀 Real Use Case from My Work I built a REST API to sync customer and order data between Odoo & a Shopify-based online store. Result: Orders synced in under 5 seconds Inventory auto-updated Manual data entry removed completely I’m growing my network with businesses who need: ✔ Custom REST API development in Odoo ✔ System integration & process automation ✔ Remote or hybrid Odoo technical expertise If your business needs clean, secure ERP APIs — happy to connect and collaborate. #OdooDeveloper #OdooConsultant #ERPImplementation #ERPOptimization #BusinessAutomation #DigitalTransformation #AustralianBusiness #SydneyTech #MelbourneTech #BrisbaneBusiness #OdooPerformance #OdooExpert #PostgreSQL #PythonDeveloper #RemoteDeveloper #HiringInAustralia #TechConsultant
To view or add a comment, sign in
-
Cache Usage in Odoo: Speed Up Your Computed Methods One of the easiest ways to improve performance in Odoo is proper use of caching. Many developers recompute values unnecessarily — slowing down reports, dashboards, and API responses. 🛠 Common Scenario A computed field is accessed hundreds of times in a loop Each access triggers the computation again System slows down unnecessarily @api.depends('line_ids.price_total') def _compute_total_amount(self): for record in self: record.total_amount = sum(record.line_ids.mapped('price_total')) If total_amount is used multiple times → recomputation happens every time. ✅ Optimize with Cache Odoo provides caching decorators: from odoo import api, models from functools import lru_cache class SaleOrder(models.Model): _inherit = "sale.order" @api.depends('order_line.price_total') @api.depends_context('uid') def _compute_total_amount(self): for record in self: record.total_amount = sum(record.order_line.mapped('price_total')) Tips: Use store=True if the field does not change often Use @lru_cache for expensive computations that can be cached globally Cache repeated database calls whenever possible 🚀 Real Impact Invoice generation: 5s → 1.2s Reduced CPU usage Reports & dashboards respond faster I’m looking to collaborate with businesses: ✔ Optimize Odoo performance ✔ Automate ERP processes ✔ Scale Odoo efficiently If your ERP system is slow or reports are lagging — let’s connect! #OdooDeveloper #OdooConsultant #ERPImplementation #ERPOptimization #BusinessAutomation #DigitalTransformation #AustralianBusiness #SydneyTech #MelbourneTech #BrisbaneBusiness #OdooPerformance #OdooExpert #PostgreSQL #PythonDeveloper #RemoteDeveloper #HiringInAustralia #TechConsultant
To view or add a comment, sign in
-
𝐓𝐫𝐨𝐛𝐳 𝐨𝐟𝐟𝐢𝐜𝐢𝐚𝐥𝐥𝐲 𝐥𝐚𝐮𝐧𝐜𝐡𝐞𝐬 𝐎𝐩𝐞𝐧𝐔𝐩𝐠𝐫𝐚𝐝𝐞 𝐀𝐏𝐈 & 𝐄𝐱𝐩𝐥𝐨𝐫𝐞𝐫 - 𝐀 𝐧𝐞𝐰 𝐜𝐨𝐧𝐭𝐫𝐢𝐛𝐮𝐭𝐢𝐨𝐧 𝐟𝐫𝐨𝐦 𝐓𝐫𝐨𝐛𝐳 𝐭𝐨 𝐭𝐡𝐞 𝐠𝐥𝐨𝐛𝐚𝐥 𝐣𝐨𝐮𝐫𝐧𝐞𝐲 𝐨𝐟 𝐎𝐝𝐨𝐨 𝐮𝐩𝐠𝐫𝐚𝐝𝐞𝐬. (𝐏𝐚𝐫𝐭 𝟐) 🗓️ 🗓️ 🗓️ After officially launching OpenUpgrade API & Explorer, Trobz continues to bring a deeper perspective into the Odoo upgrade experience with a brand-new user interface (UI) for OpenUpgrade - a space where every change is visualized, analyzed, and cross-referenced through detailed analysis files, offering a comprehensive view and streamlined control of the entire migration process from start to finish. To better understand how OpenUpgrade is redefining the standards of Odoo upgrades, let’s explore three key aspects below: 🔹 𝐎𝐩𝐞𝐧𝐔𝐩𝐠𝐫𝐚𝐝𝐞 𝐀𝐏𝐈 How has Trobz standardized the ETL (Extract – Transform – Load) process during Odoo upgrades to enable developers and consultants to query all version changes within just seconds? 🔹 𝐎𝐝𝐨𝐨 𝐌𝐨𝐝𝐮𝐥𝐞 𝐌𝐢𝐠𝐫𝐚𝐭𝐨𝐫 When the OpenUpgrade API automatically generates YAML files that are fully compatible with the Odoo Module Migrator, what real optimizations does it deliver - minimizing manual effort and improving accuracy throughout the migration process? 🔹 𝐎𝐩𝐞𝐧𝐔𝐩𝐠𝐫𝐚𝐝𝐞 𝐄𝐱𝐩𝐥𝐨𝐫𝐞𝐫 How different is the user experience when you can browse and inspect structured migration data through the clean, intuitive OpenUpgrade Explorer interface - without dealing with complex log files? 📌 📌 📌 Find the full explanation in the complete article here: https://lnkd.in/eCUXtHWE 📌 📌 📌 Experience the tool now at: https://lnkd.in/ef34hQU9 #Odoo_Migration #Odoo_Upgrade #Odoo_Partner #OCA #Trobz #Trobz_contributor #Trobz_OCA #Trobz_Odoo_Migration #Trobz_Odoo_Upgrade #Trobz_OpenUpgrade_API #Trobz_OpenUpgrade_Explorer ___________________________________ 𝐂𝐨𝐧𝐭𝐚𝐜𝐭 𝐔𝐬: ☎️ 𝐓𝐞𝐥: +84 2862-737-605 🌐 𝐖𝐞𝐛𝐬𝐢𝐭𝐞: https://trobz.com/ 📧 𝐄𝐦𝐚𝐢𝐥: contact@trobz.com 🏘𝐀𝐝𝐝𝐫𝐞𝐬𝐬: No. 13, Street 7C1, An Khanh Ward, Ho Chi Minh City, Vietnam.
To view or add a comment, sign in
-
-
SQL vs ORM Tradeoff in Odoo: When to Use Direct SQL Most Odoo developers rely only on the ORM, but for large datasets or complex reports, direct SQL can be a game-changer. Knowing when to switch can drastically improve performance. 🛑 Common Pitfalls with ORM .search() or .read() loops on thousands of records → multiple queries .mapped() on very large One2many fields → slow Complex groupings → ORM may trigger extra computations ✅ When SQL Makes Sense Scenario : Bulk reporting (100k+ records) Recommendation : Use self.env.cr.execute() Scenario : Complex joins / aggregates Recommendation: Direct SQL is faster than ORM loops Scenario : Temporary or one-time queries Recommendation : SQL reduces overhead & memory usage 🚀 Example: Fast Aggregate Report Using SQL query = """ SELECT partner_id, SUM(amount_total) AS total FROM sale_order WHERE state = 'sale' GROUP BY partner_id """ self.env.cr.execute(query) results = self.env.cr.fetchall() ✅ Fast aggregation ✅ Avoids multiple ORM queries ✅ Perfect for dashboards, exports, analytics 💡 Best Practice Use ORM first for readability & maintainability Switch to SQL only for high-volume or complex queries Always benchmark ORM vs SQL before making the decision I’m currently expanding my network and availability for Australian businesses (Sydney, Melbourne, Brisbane) who want: ✔ Odoo performance tuning ✔ ERP optimization & automation ✔ Remote or hybrid Odoo development consulting If your business wants faster, smarter, scalable ERP solutions, let’s connect! Suggested Hashtags #OdooDeveloper #OdooConsultant #ERPImplementation #ERPOptimization #BusinessAutomation #DigitalTransformation #AustralianBusiness #SydneyTech #MelbourneTech #BrisbaneBusiness #OdooPerformance #OdooExpert #PostgreSQL #PythonDeveloper #RemoteDeveloper #HiringInAustralia #TechConsultant
To view or add a comment, sign in
-
Debugging Slowness in Odoo: Using Odoo Profiler Effectively Performance issues in Odoo are common, but finding the root cause quickly is what separates good developers from great ones. 🛠 Common Symptoms of Slowness Reports or dashboards take several seconds to load Sales, inventory, or invoice lists freeze on large datasets ORM methods looping over thousands of records 🔍 How I Debug Slowness Enable Developer Mode → Odoo Profiler Check Performance tab for slow functions Identify which models and methods are taking the most time Use Python Profiling import cProfile cProfile.runctx('self.compute_heavy_method()', globals(), locals()) Shows function call time and bottlenecks SQL Query Analysis self.env.cr.execute("EXPLAIN ANALYZE SELECT * FROM sale_order") print(self.env.cr.fetchall()) Detects queries that need indexing or optimization 🚀 My Approach Identify slow ORM methods Prefetch related fields (mapped() or search_read()) Use caching for repeated computations Benchmark before & after changes Result: Real client dashboards that took 12s → 2s, with hundreds fewer SQL queries I’m looking to collaborate with Australian businesses (Sydney, Melbourne, Brisbane) who want to: ✔ Optimize Odoo performance & speed ✔ Automate ERP processes ✔ Scale Odoo without costly server upgrades If you’re facing ERP slowness or planning optimization — let’s connect! Suggested Hashtags #OdooDeveloper #OdooConsultant #ERPImplementation #ERPOptimization #BusinessAutomation #DigitalTransformation #AustralianBusiness #SydneyTech #MelbourneTech #BrisbaneBusiness #OdooPerformance #OdooExpert #PostgreSQL #PythonDeveloper #RemoteDeveloper #HiringInAustralia #TechConsultant
To view or add a comment, sign in
-
Odoo Lifesaver: Unstick Your Module with the Command Line! ⚙️ Ever been stuck with an Odoo module installation or uninstallation that freezes your database? 😩 It's a common, frustrating halt. Don't panic and don't restart your server! Here is the quick, powerful, and clean way to fix it directly using the Odoo shell 🚀. This trick is a lifesaver for module hangups, especially during migrations. The Two-Step Fix: 1️⃣ Start Odoo in Shell Mode: Use this command, replacing db_name and checking your config file name: ./odoo-bin shell -d db_name -c odoo.conf 2️⃣ Run the Immediate Uninstall Command: Once the shell is open, execute the following command, replacing 'crm' with your stuck module's technical name: self.env['ir.module.module'].search([('name', 'in', ['crm'])]).button_immediate_uninstall() ✅ That's it! The module is uninstalled cleanly and immediately, without you ever having to restart the Odoo UI. 💡 Pro Tip: Multiple Modules at Once! Need to clear a few stuck modules? List them all in the array: self.env['ir.module.module'].search([('name', 'in', ['crm', 'sale', 'purchase'])]).button_immediate_uninstall() Keep this tip in your back pocket for your next development or migration challenge! #Odoo #OdooDeveloper #OdooTip #Python #Commandline #ERP #DeveloperTools
To view or add a comment, sign in
-
-
💡 Exploring Optimizely SQL Studio — Simplifying Data Insights for Developers As Optimizely CMS developers, we often need to analyze or debug content-related data stored in the underlying database. Instead of relying on external SQL tools or direct DB access, Optimizely SQL Studio makes this process much easier and safer. 🔹 What is SQL Studio in Optimizely? Optimizely SQL Studio is a built-in or add-on tool that allows developers and administrators to run SQL-like queries directly from the CMS Admin interface. It’s primarily used for analyzing data, troubleshooting content issues, and validating relationships between CMS tables without needing full database access. 🧠 Why Developers Use It Quick data insights without connecting to SQL Server Debugging custom data stored in dynamic tables Verifying content metadata or scheduled jobs Ensuring better control and visibility for content administrators ⚙️ Real-Time Example Suppose you want to find all published pages under a specific content type, for instance, ArticlePage. You can open Admin → Tools → SQL Studio and run a query like: SELECT Name, ContentTypeID, StartPublish, Changed FROM tblContent WHERE ContentTypeID = ( SELECT pkID FROM tblContentType WHERE Name = 'ArticlePage' ) AND Status = 4 -- Published ORDER BY Changed DESC 🧩 Result: You instantly get a list of all published articles with their last modified date directly within the CMS UI. 🚀 Pro Tip: Combine SQL Studio queries with scheduled reports or dashboards to give editors real-time insights into content status, expirations, or workflow history all from within Optimizely. 💬 Closing Thought: Tools like SQL Studio bridge the gap between developers and content administrators, empowering both to understand and optimize CMS data without heavy backend dependencies. #Optimizely #CMSDevelopment #SQLStudio #DigitalExperience #WebDevelopment #OptimizelyCMS #DXP #EpiServer
To view or add a comment, sign in
-
Connect WooCommerce Data to Google Data Studio with Custom PHP Code - Brian Bateman on Splinternet Marketing & SEO — This article provides a comprehensive guide on connecting WooCommerce data to Google Data Studio using custom PHP code. By mastering this technique, businesses can improve performance through enhanced data visualization, automate reporting processes, and gain insights that drive strategic decision-making. Introduction WooCommerce is one of the leading e-commerce platforms, offering a robust solution for online businesses. To harness the full potential of data captured by WooCommerce, integrating it with Google Data Studio can provide powerful visualizations and insights. By using custom PHP code, you can create a direct data connection between WooCommerce and Data Studio, paving the way for automated and dynamic reporting. Why Connect WooCommerce to Google Data Studio? Utilizing WooCommerce data in Google Data Studio allows businesses to: Visualize Trends: Identify sales trends, customer behaviors, and product performance. Automate Reports: Reduce manual data processing and effortlessly update reports. Enhance Data Insights: Enable decision-makers to quickly interpret complex data. Connecting these platforms minimizes the traditional barriers associated with exporting and importing data, ultimately making data analysis more efficient. Prerequisites Before diving into the setup process, ensure you have the following: A WordPress site with the WooCommerce plugin installed. Access to your website's server for uploading and editing files. Basic understanding of PHP and access to your Google Account to use Data Studio. Step-by-Step Setup Step 1: Prepare Your WooCommerce Data Ensure that your WooCommerce site has active data to analyze. Identify the specific datasets you wish to connect, such as orders and products. Step 2: Create a Custom PHP Script Set up a new PHP file on your server, e.g., woocommerce-data-connector.php. Use WooCommerce functions to retrieve data: Format the data into a JSON response that Google Data Studio can interpret. Step 3: Set Up a Web API Endpoint Ensure access is configured to allow Google's servers. Create an endpoint that points to your PHP script, e.g., https://lnkd.in/gVwjQEux. Step 4: Connect to Google Data Studio Open Google Data Studio and choose to connect a new data source. Select the JSON/CSV connector in Data Studio. Enter the URL of your PHP script endpoint. Step 5: Build and Customize Reports Choose specific fields to visualize. Utilize Data Studio's features to create graphs, charts, and dashboards. Set automatic refresh schedules to keep data updated. FAQs How do I secure the API endpoint? Use basic authentication or API keys to restrict access to your data endpoint. What if I encounter data limits in Google Data Studio? Aggregate or filter your data using PHP to stay within the limits. Can I integrate other data sources in my reports? Yes, Go
To view or add a comment, sign in
-
Connect WooCommerce Data to Google Data Studio with Custom PHP Code - Brian Bateman on Splinternet Marketing & SEO — This article provides a comprehensive guide on connecting WooCommerce data to Google Data Studio using custom PHP code. By mastering this technique, businesses can improve performance through enhanced data visualization, automate reporting processes, and gain insights that drive strategic decision-making. Introduction WooCommerce is one of the leading e-commerce platforms, offering a robust solution for online businesses. To harness the full potential of data captured by WooCommerce, integrating it with Google Data Studio can provide powerful visualizations and insights. By using custom PHP code, you can create a direct data connection between WooCommerce and Data Studio, paving the way for automated and dynamic reporting. Why Connect WooCommerce to Google Data Studio? Utilizing WooCommerce data in Google Data Studio allows businesses to: Visualize Trends: Identify sales trends, customer behaviors, and product performance. Automate Reports: Reduce manual data processing and effortlessly update reports. Enhance Data Insights: Enable decision-makers to quickly interpret complex data. Connecting these platforms minimizes the traditional barriers associated with exporting and importing data, ultimately making data analysis more efficient. Prerequisites Before diving into the setup process, ensure you have the following: A WordPress site with the WooCommerce plugin installed. Access to your website's server for uploading and editing files. Basic understanding of PHP and access to your Google Account to use Data Studio. Step-by-Step Setup Step 1: Prepare Your WooCommerce Data Ensure that your WooCommerce site has active data to analyze. Identify the specific datasets you wish to connect, such as orders and products. Step 2: Create a Custom PHP Script Set up a new PHP file on your server, e.g., woocommerce-data-connector.php. Use WooCommerce functions to retrieve data: Format the data into a JSON response that Google Data Studio can interpret. Step 3: Set Up a Web API Endpoint Ensure access is configured to allow Google's servers. Create an endpoint that points to your PHP script, e.g., https://lnkd.in/gVwjQEux. Step 4: Connect to Google Data Studio Open Google Data Studio and choose to connect a new data source. Select the JSON/CSV connector in Data Studio. Enter the URL of your PHP script endpoint. Step 5: Build and Customize Reports Choose specific fields to visualize. Utilize Data Studio's features to create graphs, charts, and dashboards. Set automatic refresh schedules to keep data updated. FAQs How do I secure the API endpoint? Use basic authentication or API keys to restrict access to your data endpoint. What if I encounter data limits in Google Data Studio? Aggregate or filter your data using PHP to stay within the limits. Can I integrate other data sources in my reports? Yes, Go
To view or add a comment, sign in
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development