This this tutorial we will learn about the models and their fields in odoo apllication.
In Odoo, "models" refer to the Python classes that represent business objects or data models within the Odoo framework. These models define the structure and behavior of the data managed by Odoo applications. Models in Odoo typically correspond to database tables, and instances of these models represent records in those tables.
Here are some key aspects of models in Odoo:
Object-Relational Mapping (ORM): Odoo uses an ORM system to interact with the database. Models are defined using Python classes, and fields within these classes map to columns in the corresponding database tables. Odoo's ORM provides an abstraction layer that simplifies database interactions and reduces the need for writing raw SQL queries.
Fields: Models in Odoo are composed of fields, which represent the attributes or properties of the business objects. Fields can have different types such as Char, Integer, Float, Boolean, Date, Datetime, Text, Many2one, One2many, and Many2many. Each field specifies its data type, whether it's required, and other properties like default values, string labels, and help text.
Methods: Models can define methods that encapsulate business logic and operations related to the data model. These methods can perform various tasks such as computing derived fields, performing data validations, executing business processes, and interacting with other models.
Inheritance: Odoo supports class inheritance, allowing developers to extend and customize existing models. Inheritance can be used to add new fields, modify existing behavior, or create entirely new models based on existing ones.
Constraints and Validations: Models can define constraints to enforce data integrity rules and perform validations on the data being stored. Constraints ensure that the data conforms to the specified criteria and prevent invalid or inconsistent data from being saved to the database.
Security: Odoo provides mechanisms for controlling access to models and their records based on user roles and permissions. Access control lists (ACLs) can be defined to restrict read, write, create, and delete operations on specific models or records.
Overall, models play a central role in defining the structure, behavior, and interactions of data within Odoo applications. They serve as the foundation upon which Odoo modules are built, enabling developers to create custom business logic, integrate with external systems, and extend the functionality of the platform to meet the unique requirements of businesses.
Model fields
Fields Arguments.
Much like the model itself, fields can be configured by passing configuration attributes as parameters:
1.string (str, default: field’s name)
The label of the field in UI (visible by users).
2.required (bool, default: False)
If True, the field can not be empty. It must either have a default value or always be given a value when creating a record.
3.help (str, default: '')
Provides long-form help tooltip for users in the UI.
4.index (bool, default: False)
Requests that Odoo create a database index on the column.
You may have noticed your model has a few fields you never defined. Odoo creates a few fields in all models1. These fields are managed by the system and can’t be written to, but they can be read if useful or necessary:
1.id (Id)
The unique identifier for a record of the model.
2.create_date (Datetime)
Creation date of the record.
3.create_uid (Many2one)
User who created the record.
4.write_date (Datetime)
Last modification date of the record.
5.write_uid (Many2one)
User who last modified the record.
it is possible to disable the automatic creation of some fields
Basic template odoo models for staff model is as below:
from odoo import models,fields,api
from datetime import datetime, timedelta
class StaffMember(models.Model):
_name='staff.member'
_description='keep records of staff'
_rec_name='name'
_order='name asc'
_order='name desc'
image = fields.Binary(string='Image', attachment=True, help='profile picture \n You can not
upload file more than 10mb ')
name=fields.Char(string='Name',required=True, tracking=True,translate=True,size=20,)
email=fields.Char(string='Email address',default="admin@gmail.com")
status=fields.Selection(string='Status',selection=[('active','active'),
('inactive','inactive')],default='active',readonly=True)
dob=fields.Datetime(string='Date of Birth')
salary=fields.Float(string='Salary',trim=False)
bio=fields.Text(string='Write short bio..')
country=fields.Many2one('res.country',string='Country')
countries=fields.Many2many('res.country',string='Nearest Countries')
country_code=fields.Char(string='Country code',related='country.code')
sequence=fields.Integer(string='Seq.')
staff_contact_ids=fields.One2many('staff.member.contact','connecting_field',string='Staff
contact')
date_availability=fields.Date(copy=False,default=lambda self: (datetime.today() +
timedelta(days=90)).strftime('%Y-%m-%d'))
appointment_date = fields.Datetime(string='Appointment Date', default=fields.datetime.now(),
tracking=True)
class StaffMemberContact(models.Model):
_name='staff.member.contact'
connecting_field=fields.Many2one('staff.member',string='Staff connecting ID')
twitter=fields.Char(string='twitter')
facebook=fields.Char(string='Facebook')
youtube=fields.Char(string='Youtube')
sequence=fields.Integer(string='Seq.')
In this tutorial we will learn about the different model relationship in odoo.
in odoo basically there are three types of model relationship
1.Many2one relationship
patient_id = fields.Many2one("hospital.patient", string='Patient Name', required=True)
2.One2many relationship
this one is quite important relationship in odoo as in many case this One2many relationship is required in real project
from odoo.exceptions import ValidationError
from odoo import models, fields, api, _
class HospitalAppointment(models.Model):
_name = 'hospital.appointment'
_description = 'Appointments'
_order = "id desc"
prescription_medicine_ids = fields.One2many("hospital.appointment.prescription.medicine",
"appointment_medicine_id", string="Prescription
Medicine")
class AppointmentPrescriptionMedicine(models.Model):
_name = "hospital.appointment.prescription.medicine"
_description = "Appointment Prescription Medicine"
name = fields.Char(string="Medicine", required=True)
quantity = fields.Integer(string="Quantity")
appointment_medicine_id = fields.Many2one("hospital.appointment", string="Appointment medicine")
3.Many2many relationship
tag_ids = fields.Many2many('todo.tag', string='Tags',tracking=True)
If you see the many2many relation in database then it will create 2 different tables as
"hospital_patinet_tag_rel","patient_id","tag_id"
model fields:
1.Simple Type:
Char,Integer,Flot,Binary,Image,Date,Datetime,Selection
2.Relational Type : relation among the objects
One2many, Many2one, Many2Many,Monetory
3.Functional Type:
They are not shown in database , they are calculate in real-time base on other fields.
In Odoo, both binary and image fields are used to store binary data, but they are intended for different purposes and have different attributes. Here’s a detailed explanation of the differences between the two, along with examples.
A binary field in Odoo is a generic field for storing binary data, such as files (e.g., PDFs, documents). It is not specific to images and does not provide any image-specific functionality.
Here is an example of a binary field used to store a file in an Odoo model:
from odoo import models, fields
class Document(models.Model):
_name = 'my_module.document'
_description = 'Document'
name = fields.Char(string='Document Name', required=True)
file_data = fields.Binary(string='File', attachment=True)
file_name = fields.Char(string='File Name')
In this example:
file_data: This binary field stores the binary data of the file.file_name: This character field stores the name of the file, which can be used when downloading the file.
<record id="view_document_form" model="ir.ui.view">
<field name="name">document.form</field>
<field name="model">my_module.document</field>
<field name="arch" type="xml">
<form string="Document">
<sheet>
<group>
<field name="name"/>
<field name="file_data" filename="file_name"/>
</group>
</sheet>
</form>
</field>
</record>
An image field is a specialized binary field for storing images. It provides additional functionalities such as automatic resizing and thumbnail generation, which are useful when dealing with images.
Here is an example of an image field used to store a user profile picture in an Odoo model:
from odoo import models, fields
class UserProfile(models.Model):
_name = 'my_module.user_profile'
_description = 'User Profile'
name = fields.Char(string='User Name', required=True)
profile_picture = fields.Image(string='Profile Picture', max_width=200, max_height=200)
In this example:
profile_picture: This image field stores the binary data of the profile picture. The max_width and max_height attributes define the maximum dimensions of the image.
<record id="view_user_profile_form" model="ir.ui.view">
<field name="name">user.profile.form</field>
<field name="model">my_module.user_profile</field>
<field name="arch" type="xml">
<form string="User Profile">
<sheet>
<group>
<field name="name"/>
<field name="profile_picture" widget="image"/>
</group>
</sheet>
</form>
</field>
</record>
Purpose:
Attributes:
max_width and max_height.Functionality:
Usage in Views:
By using the appropriate field type, you can leverage Odoo's built-in functionalities to handle binary data and images more effectively.
Amanda Martines 5 days ago
Exercitation photo booth stumptown tote bag Banksy, elit small batch freegan sed. Craft beer elit seitan exercitation, photo booth et 8-bit kale chips proident chillwave deep v laborum. Aliquip veniam delectus, Marfa eiusmod Pinterest in do umami readymade swag. Selfies iPhone Kickstarter, drinking vinegar jean.
ReplyBaltej Singh 5 days ago
Drinking vinegar stumptown yr pop-up artisan sunt. Deep v cliche lomo biodiesel Neutra selfies. Shorts fixie consequat flexitarian four loko tempor duis single-origin coffee. Banksy, elit small.
ReplyMarie Johnson 5 days ago
Kickstarter seitan retro. Drinking vinegar stumptown yr pop-up artisan sunt. Deep v cliche lomo biodiesel Neutra selfies. Shorts fixie consequat flexitarian four loko tempor duis single-origin coffee. Banksy, elit small.
Reply