Enable Dark Mode!
assista-odoo-helper-for-vs-code-python-keywords.jpg
By: Cybrosys Technologies

Assista Odoo Helper for VS Code - Python Keywords

Technical Cybrosys Assista VS Code Python

In Odoo development, consistency, speed, and accuracy are critical, especially when managing complex modules and repeating similar code structures. Developers often waste valuable time rewriting boilerplate code for models, fields, views, and business logic, leading to decreased productivity and avoidable errors.

Cybrosys Assista: Odoo Helper, a powerful Visual Studio Code extension, addresses this challenge by providing a comprehensive collection of Python code snippets specifically tailored for Odoo 18. With just a few keystrokes, developers can generate clean, structured, and Odoo-compliant code—right inside VS Code.

Fully integrated into the VS Code environment, these snippets cover everything from field declarations, model definitions, and decorators to CRUD operations, exception handling, and more. This not only accelerates development but also ensures best practices are consistently followed.

In this guide, you'll find the complete list of supported snippet keywords, designed to help you write efficient, error-free Odoo code directly from your favorite editor.

Python Field Snippets

These snippets streamline the creation of common Odoo fields:

* Odoo Boolean Field

Defines a true/false field with optional change tracking support.

fields.Boolean(
    string="Name",
    help="Help text",
    default=False,
    tracking=True
)

* Odoo Binary Field

Used to store binary data, such as files or images, with optional size limits.

fields.Binary(
    string="Name",
    help="Help text",
    attachment=True,
    max_size=10
)

* Odoo Char Field

A basic string field for short text with optional translation and tracking support.

fields.Char(
    string="Name",
    help="Help text",
    required=False,
    tracking=True,
    translate=True
)

* Odoo Integer Field

A field for storing integer numbers with optional tracking.

fields.Integer(
    string="Name",
    help="Help text",
    default=0,
    tracking=True
)

* Odoo Image Field

A field for storing and managing images with optional size limits.

fields.Image(
    string="Name",
    help="Help text",
    max_width=1024,
    max_height=1024
)

* Odoo Float Field

A field for storing decimal numbers with precision control and optional tracking.

fields.Float(
    string="Name",
    help="Help text",
    digits=(16, 2),
    tracking=True
)

* Odoo Text Field

A field for storing longer text strings with optional translation support.

fields.Text(
    string="Name",
    help="Help text",
    translate=True
)

* Odoo Html Field

A field for storing HTML content with sanitization and translation support.

fields.Html(
    string="Name",
    help="Help text",
    sanitize=True,
    translate=True
)

* Odoo Date Field

A field for selecting and storing dates with optional tracking.

fields.Date(
    string="Name",
    help="Help text",
    tracking=True
)

* Odoo Datetime Field

A field for selecting and storing date-time values with optional tracking.

fields.Datetime(
    string="Name",
    help="Help text",
    tracking=True
)

* Odoo Selection Field

Allows selection from a predefined list of options with optional tracking.

fields.Selection([
    ('draft', 'Draft'),
    ('confirmed', 'Confirmed'),
    ('done', 'Done')
],
string="Status",
default='draft',
tracking=True,
help="Help text")

* Odoo Many2one Field

Links to a single record of another model with company validation and tracking.

fields.Many2one(
    'model.name',
    string="Name",
    help="Help text",
    tracking=True,
    ondelete='cascade',
    check_company=True
)

* Odoo Many2many Field

Represents a many-to-many relationship between models with company validation and tracking.

fields.Many2many(
    'model.name',
    string="Name",
    help="Help text",
    tracking=True,
    check_company=True
)

* Odoo Monetary Field

Used for storing monetary values with currency tracking.

fields.Monetary(
    string="Name",
    help="Help text",
    currency_field="currency_id",
    tracking=True
)

* Odoo One2many Field

Represents a one-to-many relationship with optional tracking support.

fields.One2many(
    'model.name',
    'connection_field',
    string="Name",
    help="Help text",
    tracking=True
)

* Odoo Reference Field

Dynamic field that can reference records from multiple models.

fields.Reference(
    string="Name",
    selection=[
        ('model1', 'Model 1'),
        ('model2', 'Model 2')
    ],
    help="Help text"
)

* Odoo Json Field

A field for storing JSON data structures in the database.

fields.Json(
    string="Name",
    help="Help text"
)

Import Statements

* Odoo import http request – Import Http Request declarations:

from odoo.http import request

* Odoo import api– Import decorators and API methods:

from odoo import api

* Odoo import base64 – Import base64:

import base64

* Odoo import common– Import Odoo common imports:

from odoo import api, fields, models

* Odoo import config– Import configuration utilities:

from odoo.tools import config

* Odoo import date_utils – Import date utility helpers:

from odoo.tools import date_utils

* Odoo import datetime – Import datetime module:

from datetime import datetime, date, timedelta

* Odoo import exceptions – Import Odoo-specific exception classes:

from odoo.exceptions import UserError, ValidationError

* Odoo import fields – Import Odoo field classes:

from odoo import fields

* Odoo import json – Import json:

import json

* Odoo import logging – Import Python logging module:

import logging
_logger = logging.getLogger(__name__)

* Odoo import models – Import Odoo model classes:

from odoo import models

* Odoo import re – Import Python regex module:

import re

* Odoo import tools – Import Odoo utility functions:

from odoo import tools

Exception Handling

* Odoo import exceptions – Import common Odoo exceptions:

from odoo.exceptions import UserError, ValidationError

* Odoo User Error – Raise a UserError:

raise UserError("User error message")

* Odoo Validation Error  – Raise a ValidationError:

raise ValidationError("Validation error message")

* Odoo Access Error – Raise an AccessError:

raise AccessError("Access error message")

* Odoo Missing Error – Raise a MissingError:

raise MissingError("Missing error message")

* Odoo Redirect Warning – Raise a RedirectWarning:

raise RedirectWarning("Warning message", action_id, "Button Label")

Model Class Templates

* Odoo Abstract Model
Creates a model that serves as a base for other models; no database table is created.
from odoo import api, fields, models
class ModelName(models.AbstractModel):
    _name = 'model.name'
    _description = 'Model Description'
    name = fields.Char(string='Name', required=True)
    active = fields.Boolean(string='Active', default=True)
* Odoo Transient Model
Creates a temporary model for wizard-like functionality. Records are auto-deleted after use.
from odoo import api, fields, models
class ModelName(models.TransientModel):
    _name = 'model.name'
    _description = 'Model Description'
    name = fields.Char(string='Name', required=True)
    active = fields.Boolean(string='Active', default=True)
* Odoo New Model Class
Creates a new Odoo model class with a basic structure for storing data and defining logic.
from odoo import fields, models 
class ModelName(models.Model):
    _name = 'model.name'
    _description = 'Model Description'
    name = fields.Char(string='Name', required=True)
* Odoo Classical Inherited Model Class
Creates an inherited Odoo model class to extend and enhance an existing model.
from odoo import fields, models
class ModelName(models.Model):
    _name = 'model.name'
    _inherit = 'model.to.inherit'
    _description = 'Model Description'
    new_field = fields.Char(string='New Field')
* Odoo Delegated Inherited Model Class
Creates a new model that inherits fields from another model using delegation.
from odoo import fields, models
class ModelName(models.Model):
    _name = 'model.name'
    _inherits = {'parent.model': 'parent_id'}
    _description = 'Model Description'
    parent_id = fields.Many2one('parent.model', required=True, ondelete="cascade")
* Odoo Extended Inherited Model Class
Extends an existing model to add custom methods or logic.
from odoo import fields, models, api
class ModelName(models.Model):
    _inherit = 'model.to.extend'
    @api.model
    def create(self, vals):
        # Custom logic before creation
        res = super().create(vals)
        # Custom logic after creation
        return res

Common Methods

* Odoo Create Method

Overrides the create method to add custom logic when new records are created in Odoo models.

@api.model_create_multi
def create(self, vals_list):
    # Pre-create logic (optional)
    records = super().create(vals_list)
    # Post-create logic (optional)
    return records

* Odoo Write Method

Overrides the write method to apply custom logic whenever records are updated.

def write(self, values):
    # Pre-write logic (optional)
    res = super().write(values)
    # Post-write logic (optional)
    return res

* Odoo Unlink Method

Overrides the unlink method to implement custom logic when records are deleted.

def unlink(self):
    # Pre-unlink logic (optional)
    res = super().unlink()
    # Post-unlink logic (optional)
    return res

* Odoo Onchange Method

Adds interactive behavior to forms by dynamically updating field values based on changes in related fields.

@api.onchange('field_name')
def _onchange_field_name(self):
    if self.field_name:
        self.target_field = value

* Odoo Compute Method

Automatically computes field values based on defined dependencies, updating in real time when related fields change.

field_name = fields.FieldType(
    string='Field Label',
    compute='_compute_field_name',
    store=True
)
@api.depends('dependency_field')
def _compute_field_name(self):
    for rec in self:
        # Compute logic
        rec.field_name = value

* Odoo Constraints Method

Applies model-level validations that are automatically checked during record creation and updates.

@api.constrains('field_name')
def _check_field_name(self):
    for rec in self:
        if not rec.field_name:
            raise ValidationError("field_name must be set")

* Odoo Search Method

Implements custom search logic for your model, useful for name-based searches or advanced domain filtering.

@api.model
def _search_name(self, name, args=None, operator='ilike', limit=100, name_get_uid=None):
    args = args or []
    domain = []
    if name:
        domain = ['|', '|',
            ('name', operator, name),
            ('field_name', operator, name),
            ('field_name2', operator, name)]
    return self._search(domain + args, limit=limit, access_rights_uid=name_get_uid)

* Odoo Default Get Method

Specifies default field values that are automatically applied when new records are created.

@api.model
def default_get(self, fields_list):
    res = super().default_get(fields_list)
    res.update({
        'field_name': default_value,
    })
    return res

* Odoo Action Method

Defines methods that generate action dictionaries to open views or execute specific actions in Odoo.

def action_action_name(self):
    self.ensure_one()
    return {
        'name': _('Action Title'),
        'type': 'ir.actions.act_window',
        'res_model': 'model.name',
        'view_mode': 'list,form',
        'domain': [('field', '=', self.field)],
        'context': {'default_field': self.field},
    }

* Odoo sql constraints

Ensures data accuracy by applying constraints directly at the database level.

_sql_constraints = [
    ('constraint_name', 'constraint_type', 'message')
]

Conclusion

The Python snippet keywords available in Cybrosys Assista, Odoo Helper for VS Code are crafted to simplify and speed up everyday Odoo development tasks. From defining fields and models to handling exceptions and CRUD operations, these snippets help you write clean, consistent code without repeating the basics every time.

Whether you're creating a new module or enhancing an existing one, these ready-to-use snippets offer a solid starting point for faster, error-free development. By integrating them into your VS Code workflow, you can concentrate more on business logic and less on repetitive boilerplate.


If you need any assistance in odoo, we are online, please chat with us.



0
Comments



Leave a comment



whatsapp_icon
location

Calicut

Cybrosys Technologies Pvt. Ltd.
Neospace, Kinfra Techno Park
Kakkancherry, Calicut
Kerala, India - 673635

location

Kochi

Cybrosys Technologies Pvt. Ltd.
1st Floor, Thapasya Building,
Infopark, Kakkanad,
Kochi, India - 682030.

location

Bangalore

Cybrosys Techno Solutions
The Estate, 8th Floor,
Dickenson Road,
Bangalore, India - 560042

Send Us A Message