How to apply an domain on relational field odoo? - odoo

Here is my sale.order.line module, I do some modifications
I want to apply a domain on the product that not all product be displayed just products in Ligne contract field for example :
Here in my Contrat line, I Have just one Product so on the Sale order lines only this product (article) must be shown

Use onchane event for this in your sale.order.line
#api.onchange('contrat_id')
def set_domain(self):
# force the user to reselect the producg if he changes the contrat line
self.product_id = False
if self.contrat_id :
return {'domain': {'product_id': [('id', 'in', self.contrat_id.product_ids.ids)]}}
else:
# remove the domain if no contrat is selected
return {'domain': {'product_id': []}}
I'm using my phone sorry if i made a syntax error but I hope you get the idea
Edits
Okay in your contract model you don't have a many2many field to product model as I thought instead you have this one2many field ligne contract
So let suppose that the name of that field is ligne_ids in this one2many relation there is a many2one field to product model let us say its name is product_id.
Use the power of mapped to extract in one line all product ids in the contract lignes.
# many2one -> one2many -> mapped('many2one') this will collect of the records without duplication from the o2m field.
# contract -> contract lignes -> products
self.contrat_lignes_id.ligne_ids.mapped('product_id').ids
Hope this helps you

Related

How to store relational fields to the database?

I've been searching for this for a week now, and still don't find any satisfying answer. If we make any type of relationship to other model in Odoo (in any framework as well) it won't store the data inside it, it will only store its id. Now when the related model get changed, the change will also true for all the child models that's inheriting it.
I want just like in the Sale module, when I change any product in Products model, it doesn't change the same product that's already stored in the orders. Please, any help, I'm very new here to Odoo I used to develop with Java.
An order correspond to the model named sale.order which is in one2many relationship with the model sale.order.line (SOL). one SOL has it s OWN fields for price, vat... which are computed bases on the current state of product at the time of the customer order. That's why the order and its SOL are not updated when the corresponding product attributes (price...) are changed...
In Odoo : an inherited python class EXTENDS the original class (similar to java extends) : in the sale_coupon module, the model located at src/odoo/addons/sale_coupon/models/sale_order.py is :
class SaleOrder(models.Model):
_inherit = "sale.order"
extends the source class SaleOrder defined in the module sale : src/odoo/addons/sale/models/sale.py:
class SaleOrder(models.Model):
name = "sale.order"
That's mean that the inherited class SaleOrder (_inherit) gets the specific attributes (fields) and methods (def) provided and defined in its source(s) class(es) : saleOrder :
origin = fields.Char(string='Source Document', help="Reference of the document that generated this sales order request.")
def _amount_all(self):
""" Compute the total amounts of the SO."""
for order in self:
amount_untaxed = amount_tax = 0.0
for line in order.order_line:
amount_untaxed += line.price_subtotal
amount_tax += line.price_tax
...
And you can add new fields and new methods in your inherited class SaleOrder scope :
reward_amount = fields.Float(compute='_compute_reward_total')
def action_confirm(self):
self.generated_coupon_ids.write({'state': 'new'})
...
return super(SaleOrder, self).action_confirm()
But, you don t need to instantiate theses Classes in your code (you don t need to create yourself Objects).
Theses classes have the basic CRUD-methods provided from models.Model: def create(), def read(), def write(), def unlink()
The source and the inherited class(es) both are connected to the same database-table : sale_order
So one Class-record (python in Odoo) :
self.env['sale.order'].browse(12)
corresponds to one record in the database-table : sale_order
Theses classes (SaleOrder) have the CRUD-methods from model.Model : def create(), def read(), def write(), def unlink() and they can override them in their own scope, where you can optionally call the "parent"-def : super(SaleOrder, self).unlink() :
def unlink(self):
for order in self:
if order.state not in ('draft', 'cancel'):
raise UserError(_('You can not delete a sent quotation or a confirmed sales order. You must first cancel it.'))
return super(SaleOrder, self).unlink()
Relations betweens models are defined using fields :
A relation between the sale.order model and the res.partner model (contact) is created using fields.Many2one:
class SaleOrder(models.Model):
...
partner_id = fields.Many2one('res.partner')
which is reflected in the corresponding database-table.
First of all, If you change the product details It will these details will change accordingly in the sale order after you refresh, about store the id of relation field its the standard way to use,
but there Is another way I think this is the way you looking for which Is store data as a JSON in column with type JSON as an example for sale order line table if you want to store the product as a JSON column it will be like below:
[{"id": 1, "name": "product 1"},]
of course, there Is a way to read and update and create the data into a JSON column you can read about It.
one more way as an example if you want to store the product to the current record of relation table not just store the Id and query to get the result you can just create new fields for data you want to store like if you want to store the name and price with name and id then you must add fields for this date and when you create in order line rather than add just product Id as a relation just add the product data to the new fields you have added before but this is not a good way.
I hope I understand your question and this answer helps you.

how to get only child name not with parent name in many2many field with many2many_tags widget odoo?

I have the Customer field in the Sale Order form.
I have added a new Many2many field with many2many_tags for Child Contacts of Customers in the Sale order form.
Now when I change Customer this new field fills with its child contacts.
But it comes with a Customer name.
I want to display only the name of child contacts.
Thanks in Advance.
You should inherit the name_get method like below.
#api.multi
def name_get(self):
if not self._context.get('ADD_CONTEXT_ON_SALEORDER_ACTION_AND_ALSO_ON_FIELD'):
return super(ResPartner, self).name_get()
res = []
for partner in self:
res.append((partner.id, partner.name))
return res
as per above code you also you need to add context in sale order action and on that many2many field too.
The values are coming from js file of many2many_tags
In this it shows values of display_name.
You can change the code as per your need.

How can I show one2many field of another model in my form view

I have a custom object "Car" with a one2many relationship to another object "Trips" which captures the various trips made by the car.I added the trips to the form view of the car so i can see all the trips made by each car. I created a custom many2one field in sale.order called "x_car" related to "Car" and added it to the sale.order form view. Now i want to add a one2many field too, which will show the trips of the car when it is selected in the sale.order form view. How can i achieve that?
I have already tried to create a one2many field in sale.order (trips,car_id) and set related to x_car.trips
I hoped it would pull all the records from Trips based on the selected x_car, but it does not return any data. I know a one2many relationship would typically be based on the object_id (in this case sale_order_id) but is there a way to base it on x_car?
You can use a computed many2many field for such purposes:
class SaleOrder(models.Model):
_inherit = "sale.order"
car_id = fields.Many2one(comodel_name="car")
trip_ids = fields.Many2many(
comodel_name="trip", string="Trips",
compute="_compute_trip_ids")
#api.multi
#api.depends('car_id')
def _compute_trip_ids(self):
for order in self:
order.trip_ids = order.car_id.trip_ids.ids
I bet your field names or a bit off of my example, but i always try to stick to the Odoo guidelines. Just substitute them with your names ;-)

How to filter Many2one value depend another field?

please I have a custom module here is a capture :
then I go to Sales order and modify the module sale.order.line i add some fields in relation with my custom module
Now my request is in ligne contrat i want only lignes in the contrat
for example if i choose Contrat 01 only ligne in Contrat 01 like this
here is my code :
You can use a domain in the field definition in your XML:
<field name="contrat_name_id"/>
<field name="contrat_lignes_id" domain="[('ligne_ids', '=', contrat_name_id)]"/>
This will filter contrat_lignes_id to only show records where ligne_ids matches what you entered for contrat_name_id on that line.
What #djames did will work only in this form view if you want
to have this behavior in all your sale.order.line views use python
to do this job for you.
class bons_lines(model.Model):
_inherit = 'sale.order.line'
# your new fields
....
....
#api.onchange('contrat_name_id')
def onchange_contrat_name(self):
if self.contrat_name_id:
# add the domain
self.contrat_lignes_id = False # force the user to reselect the contrat_lignes_id if he changes the contrat name
return {'domain': {'contrat_lignes_id': [('ligne_ids', '=', self.contrat_name_id.id)]}}
else:
# remove the domain
return {'domain': {'contrat_lignes_id': []}}
This way you will not have to add the domain in every XML view you declare.

Show a many2many field as a many2one

I have a field many2many and in a specific view I need to show it as a many2one, or imitate the behavior of the many2one fields (restrict that only one record can be added and if the user select another record, the one that had previously selected will be deleted). In the view I declared:
<field name="employee_ids" widget="many2one" />
but it gave me the following error:
TypeError: 'int' object is not iterable
Is there any way to achieve this?
I think you can force the user to select only one record by
using onchange decorator:
#api.onchange('employee_ids')
def force_one_selection(self):
"""Force the user to select only one record"""
if self.employee_ids and len(self.employee_ids) > 1:
# user has added a new record
self.employee_ids = [(6, 0, self.employee_ids[0].id)] # you can change the index to 1
# and you can return a warning here to tell the user that he should not select more than
# one record