Call us today!

+91 93422 58771

How can you create, write, Fields View Get, and unlink records in Odoo?

Odoo is a powerful open-source ERP platform that allows businesses to streamline operations, manage workflows, and improve productivity. One of the key advantages of Odoo is its flexibility, enabling developers to customize core functionalities by overriding default methods.

In this blog, we will explore some of the most essential Odoo functions used to create, update, modify views, and delete records. Understanding these functions will help developers enhance Odoo applications efficiently and tailor them to meet business needs.

1. Create Function in Odoo

The create function in Odoo is used to add new records to a model. This method can be overridden to extend or modify the default record creation logic.

Example:

from odoo import models, fields, api 

class CustomModel(models.Model): 
 _name = 'custom.model'     
name = fields.Char(string='Name')    
@api.model     def create(self, values):        
 """Custom logic before creating the record"""       
 if 'name' in values and not values['name']:             
raise ValueError("Name field cannot be empty!")       

 # Call Odoo's default create method        
 record = super(CustomModel, self).create(values)         
return record

Explanation:

  • The @api.model decorator ensures that the function works at the model level.
  • The values dictionary contains the data that will be used to create the new record.
  • The function validates the data (e.g., ensuring the name field is not empty).
  • The super(CustomModel, self).create(values) call preserves Odoo’s default functionality.

When to Use?

  • When you need to validate data before inserting it.
  • If you want to automatically set default values.
  • To trigger custom logic (like sending notifications) when a record is created.

2. Write Function in Odoo

The write function is used to update existing records in a model. Overriding this function allows you to customize how data is modified.

Example:

class CustomModel(models.Model):     
_name = 'custom.model'     

@api.multi    
 def write(self, values):         
"""Custom logic before updating records"""        
if 'name' in values and not values['name']:            
 raise ValueError("Name cannot be empty when updating!")        

 # Call Odoo's default write method         
return super(CustomModel, self).write(values)

Explanation:

  • The function checks if the name field is present and prevents updates with empty values.
  • It ensures data integrity while allowing updates.
  • super(CustomModel, self).write(values) ensures the original Odoo functionality remains intact.

When to Use?

  • To validate or modify data before updating a record.
  • When you want to trigger custom logic (e.g., updating related records).
  • If you need to restrict certain fields from being updated based on conditions.

3. Fields View Get Function in Odoo

The fields_view_get function is used to dynamically modify Odoo views (like form or tree views) without changing XML files manually. This is useful when you want to add fields, modify layouts, or control visibility based on conditions.

Example:

from lxml import etree 

class CustomModel(models.Model):     
_inherit = 'crm.lead'     

@api.model     
def fields_view_get(self, view_id=None, view_type='form', toolbar=False,
submenu=False):        
  res = super(CustomModel, self).fields_view_get(view_id=view_id,
view_type=view_type, toolbar=toolbar, submenu=submenu)         
if view_type == 'form':             
doc = etree.XML(res['arch'])             
for node in doc.xpath("//form"):                 
node.append(etree.Element('field', name='priority', string='Lead Priority'))             
res['arch'] = etree.tostring(doc, encoding='unicode')         
elif view_type == 'tree':
doc = etree.XML(res['arch'])             
for node in doc.xpath("//tree"):
node.append(etree.Element('field', name='stage_id', string='Stage'))             
res['arch'] = etree.tostring(doc, encoding='unicode')         
return res

Explanation:

  • This function modifies both form and tree views dynamically.
  • etree.XML() is used to parse and manipulate the existing XML structure.
  • The function adds new fields dynamically without modifying XML files.

When to Use?

  • When you need to customize Odoo views dynamically.
  • To show/hide fields based on conditions.
  • To extend the UI without modifying XML files.

4. Unlink Function in Odoo

The unlink function is used to delete records. Overriding this function allows developers to restrict deletions based on conditions.

Example:

from odoo import exceptions 
class CustomModel(models.Model):     
_inherit = 'account.move.line'     
@api.multi     
def unlink(self):
for record in self:             
if record.move_id.state == 'posted':
raise exceptions.UserError("You cannot delete journal items from a posted entry.")         
return super(CustomModel, self).unlink()

Explanation:

  • The function loops through the selected records.
  • If a record is in a ‘posted’ state, deletion is prevented.
  • exceptions.UserError is used to display a warning message.
  • Otherwise, super(CustomModel, self).unlink() is called to perform the default deletion process.

When to Use?

  • When deletion must be restricted based on conditions.
  • To log deletion activity for auditing.
  • If certain records should never be deleted (e.g., invoices, posted transactions).

Conclusion

These core Odoo functions—create, write, fields_view_get, and unlink—are essential for developers who want to customize and enhance Odoo modules. By overriding these methods, you can:

  • Ensure data integrity by adding validations.
  • Dynamically modify Odoo views to improve user experience.
  • Implement custom logic for creating, updating, and deleting records.

Mastering these functions will help you build powerful, flexible, and business-oriented Odoo applications.

🔹 Want more Odoo development tips? Stay tuned for our next blog post!

Need Odoo customization? Contact us for expert solutions!