Member-only story
π Connecting Odoo with a MySQL Database using PyMySQL: A Practical Guide
When building scalable enterprise solutions with Odoo, there are times you need to connect to external databases to enrich your models with data from legacy systems or third-party applications. In this article, I will demonstrate how to integrate an external MySQL database with your Odoo custom module using the lightweight and powerful PyMySQL library.
π¦ Why PyMySQL?
PyMySQL is a pure Python MySQL client library that allows easy database operations without any C dependencies, making it ideal for Odoo deployments on various Linux servers or containers.
π§ Step 1: Install the Required Library
First, ensure pymysql is installed in your Odoo environment:
pip install pymysqlπ Step 2: The Python Code for Database Connection
Below is a practical implementation within an Odoo model to connect to a MySQL database, fetch buyer data, and dynamically populate a selection field.
from odoo import api, fields, models, _
import pymysql
from pymysql.cursors import DictCursor
import logging
logger = logging.getLogger(__name__)
class BuyerReport(models.Model):
_name = 'buyer.report'
_inherit = ['mail.thread', 'mail.activity.mixin']
_description = 'Buyer Report'
def _connect_to_db(self):
try:
connection =β¦