How to Create Mixins in Odoo 18

it's a necessity. Whether you're building custom modules or extending the core functionality of Odoo 18, understanding Mixins is essential.

In the world of Odoo development, writing clean, maintainable, and reusable code is more than just best practice — it's a necessity. Whether you're building custom modules or extending the core functionality of Odoo 18, understanding Mixins is essential. Mixins let you modularize functionality so that it can be shared across models without repetition. If you're working on an ERP for Small Companies, especially those needing scalable and flexible solutions, this concept is a game changer.

In this guide, we’ll walk you through what Mixins are in Odoo 18, why they matter, and how you can create your own. By the end, you'll know exactly how to build and use Mixins to elevate your development game.

? What Are Mixins in Odoo?

Mixins in Odoo are abstract models designed to add reusable logic across multiple models. They're not meant to stand alone but to be inherited by other models to share behavior.

Think of them as little toolkits. Instead of rewriting the same logic (like automatic timestamps, status logging, or email formatting) in several models, you can encapsulate that functionality in a Mixin — and reuse it anywhere with a single line of inheritance.

Common examples of built-in Mixins in Odoo include:

  • mail.thread: For enabling chatter functionality
  • portal.mixin: To expose records on customer portals
  • utm.mixin: For tracking UTM parameters in marketing

? Why Use Mixins? Benefits for Odoo Developers

Before we dive into code, let’s look at the main benefits:

1. Code Reusability

Mixins allow you to DRY (Don't Repeat Yourself) your code. Instead of duplicating logic across models, you define it once in a Mixin.

2. Clean Architecture

Your code becomes more modular and easier to maintain. Changes in one place reflect everywhere the Mixin is used.

3. Separation of Concerns

Mixins help separate features into independent blocks. This makes your code easier to debug, test, and evolve over time.

?️ How to Create a Custom Mixin in Odoo 18

Let’s say you want to log every time a record is created or modified in certain models. Instead of adding the same code in multiple models, we can create a Mixin.

Here’s a step-by-step walkthrough.

Step 1: Define Your Mixin

Create a Python file in your custom module, for example: models/logger_mixin.py

python

from odoo import models

import logging

 

_logger = logging.getLogger(__name__)

 

class LoggerMixin(models.AbstractModel):

    _name = 'logger.mixin'

    _description = 'Logger Mixin'

 

    def create(self, vals):

        _logger.info(f"Creating record with values: {vals}")

        return super(LoggerMixin, self).create(vals)

 

    def write(self, vals):

        _logger.info(f"Updating record {self} with values: {vals}")

        return super(LoggerMixin, self).write(vals)

Key Notes:

  • We inherit from models.AbstractModel — this tells Odoo it's a Mixin.
  • We override create and write to insert logging functionality.

Step 2: Use the Mixin in Your Models

Let’s say you have a model called property.listing. To use your Mixin:

python

from odoo import models, fields

 

class PropertyListing(models.Model):

    _name = 'property.listing'

    _inherit = ['logger.mixin']

 

    name = fields.Char(string='Property Name')

    price = fields.Float(string='Listing Price')

That’s it! Now, every time a property.listing record is created or updated, it logs the activity using the shared logic from the Mixin.

? Testing Your Mixin

Don’t just code — test!

Fire up your Odoo shell:

bash

$ odoo shell -d your_db_name

Then try:

python

CopyEdit

env['property.listing'].create({'name': 'Beach House', 'price': 250000})

Check your logs. You should see the line:

pgsql

INFO:odoo.addons.your_module.models.logger_mixin:Creating record with values: {'name': 'Beach House', 'price': 250000}

Congratulations — your Mixin works!

? Advanced Use Cases for Mixins

Mixins can be used for much more than logging. Here are a few advanced ideas:

1. Access Control

Create a Mixin that checks user roles before allowing certain operations.

2. Default Notifications

Auto-generate notifications when records are updated or deleted.

3. Soft Deletion

Override the unlink() method to flag records as inactive instead of permanently deleting them.

4. Common Computed Fields

Share computed fields (like age based on birthdate) across multiple models.

Each of these features, when bundled into a Mixin, saves hours of work and keeps your codebase lean.

? Best Practices for Using Mixins

Here are some quick do's and don'ts:

✅ Do:

  • Give your Mixin a clear _name and _description
  • Use models.AbstractModel as the base
  • Document what the Mixin does
  • Keep the Mixin small and focused on one task

❌ Don't:

  • Add fields or logic irrelevant to the models using it
  • Use Mixins where regular inheritance or delegation makes more sense
  • Forget to test behavior across all models that inherit from the Mixin

? Where to Place Mixins in Your Custom Module

Stick to the conventional module structure:

markdown

your_module/

├── models/

│   ├── __init__.py

│   ├── logger_mixin.py

│   └── property_listing.py

├── __manifest__.py

In your __init__.py, make sure to import your Mixin:

python

from . import logger_mixin

from . import property_listing

Proper organization goes a long way in maintainability, especially in larger Odoo projects.

? Final Thoughts: Mixins Are a Developer's Secret Weapon

Mixins are one of the most underused yet powerful features in Odoo. They promote clean code, modularity, and reusability — all vital when you're building scalable ERP solutions.

Whether you're developing a complex enterprise solution or tailoring an ERP for Small Companies, mastering Mixins allows you to deliver faster, more robust features with less code.

✅ Need Help with Odoo Development?

If you're looking to streamline your Odoo 18 implementation or need help creating advanced Mixins, don't go it alone. Hire a professional Odoo Implementation Consultant who can accelerate your project, avoid common pitfalls, and ensure your ERP system is future-ready.

? Contact me today to get expert support from certified Odoo developers.


Luke Oliver

1 ब्लॉग पदों

टिप्पणियाँ