A record from a model may be related to a record from another model. Relational fields link records, either of the same model (hierarchies) or between different models. Here 3 types of Relations are introduced below.
-
In our
appointment.py
file, an appointment have a connection to a patient. The value of this field is a record of a model that is associated withkmhospital.patient
. For this we have to addMany2one
fields to the models and add them in the views. -
Remember: By convention,
Many2one
fields have the_id
suffix.patient_id = fields.Many2one("kmhospital.patient", string='Patient Name', required=True)
-
Add that field to the tree and form view in the
appointment_view.xml
.<field name="patient_id"/>
-
After selecting the patient name, the patient age, gender, phone and email will automatically be updated for the patient by using the
related
field.phone = fields.Char(string='Phone', related='patient_id.phone') email = fields.Char(string='Email', related='patient_id.email') age = fields.Integer(string='Age', related='patient_id.age')
Here
patient_id
is theMany2one
field and it will come fromkmhospital.patient
model.
It is bidirectional multiple relationship field, any record on one side can be related to any number of records on the other side.
-
In
appointment.py
file,Many2many
is used to add the multiple medical test. By convention, Many2many fields have the_ids
suffix.prescription_medical_test_ids = fields.Many2many("kmhospital.medicaltest", "medical_test_ids", string="Medical tests")
-
We also have to add another
Many2many
field for the medical test inmedicaltest.py
.medical_test_ids = fields.Many2many(string="Medical tests")
-
Add the field in the views file
appointment_view.xml
in tree and from view.<field name="prescription_medical_test_ids"/>
-
In
appointment.py
file,One2many
is used to store multiple records of medicine. By convention, One2many fields have the_ids
suffix.prescription_medicine_ids = fields.One2many("kmhospital.appointment.prescription.medicine", "appointment_medicine_id", string="Prescription Medicine")
-
As One2many is a virtual relationship, there must be a Many2one field in the other model, in our case the model is
kmhospital.appointment.prescription.medicine
, and the field name must be related field likeappointment_medicine_id
.appointment_medicine_id = fields.Many2one("kmhospital.appointment", string="Appointment medicine")
-
Add the view to the
appointment_view.xml
.<field name="prescription_medicine_ids"/>
-
As this field is an editable field we have to change it with tree and from view.
<field name="prescription_medicine_ids"> <tree editable="bottom"> <field name="name"/> <field name="quantity"/> </tree> <form> <group> <group> <field name="name"/> </group> <group> <field name="quantity"/> </group> </group> </form> </field>