cannot add fields to a many2many relation class - odoo

I created a site class having many2many relation with text class. I'm trying to add some attributes to the many2many relation class.
This is the site class:
class site(models.Model):
_name ='ab.site'
name = fields.Char('Name')
text_ids = fields.Many2many('ab.site.text',
'ab_site_text_rel',
'text_id',
'site_id',
'Texts')
This is the text class:
class text(models.Model):
_name = 'ab.text'
name = fields.Char('Title', required=True)
I need to create a non-conformity depending at the same time on the text class and the site class, the user can add a list of non-conformities in the site depending on legal texts, so the non-conformity class is related to both, that's why I'm trying to add it to the relation class.
I create the relation class, I added the applicability field (boolean) and a one2many field (non-conformities):
class ab_site_text_rel(models.Model):
_name = "ab.site.text.rel"
_rec_name = "site_id"
site_id = fields.Many2one('ab.site', 'Site', ondelete='cascade')
text_id = fields.Many2one('ab.site.text', 'Text', ondelete='cascade')
applicability = fields.Boolean(string='Applicability')
nonconformity_ids = fields.One2many('ab.nonconformity','ab_site_text_rel','Non-conformities')
I got this key error when running the server:
File "/home/euromed/git/odoo9/openerp/modules/registry.py", line 200, in setup_models
model._setup_fields(cr, SUPERUSER_ID, partial)
File "/home/euromed/git/odoo9/openerp/api.py", line 250, in wrapper
return old_api(self, *args, **kwargs)
File "/home/euromed/git/odoo9/openerp/api.py", line 354, in old_api
result = method(recs, *args, **kwargs)
File "/home/euromed/git/odoo9/openerp/models.py", line 3046, in _setup_fields
field.setup_full(self)
File "/home/euromed/git/odoo9/openerp/fields.py", line 495, in setup_full
self._setup_regular_full(model)
File "/home/euromed/git/odoo9/openerp/fields.py", line 1893, in _setup_regular_full
invf = comodel._fields[self.inverse_name]
KeyError: 'ab_site_text_rel'

Relational Fields:
Relational fields are fields with values that refer to other objects. Relationship can be Unidirectoinal or Bi-directional.
In general, there are main three types of relation.
1. Many2one
Normal relationship towards to other objects (using a foreign key)
Invoice lines contains reference of invoice (invoice_id)
invoice_id = fields.Many2one(comodel_name='account.invoice', string='Invoice')
2. One2many
Virtual relationship towards multiple objects (inverse of many2one).
A one2many relational field provides a kind of “container” relation:
the records on the other side of the Relation can be seen as
“contained” in the record on this side.
In a one-to-many relationship between Table A and Table B the rows in
Table A are linked to zero, one, or many rows in Table B. This
relationship allows information to be saved in a table and referenced
many times in other tables.
invoice_line = fields.One2many(comodel_name='account.invoice.line', inverse_name='invoice_id', string='Invoice Line')
3. Many2many
Bi-directional multiple relationship between objects.
This is the most general kind of relation: a record may be related to any number of records on the other side, and vice-versa.
In the case of a many-to-many relationship, each row in Products is linked to zero, one or many rows in Taxes and vice versa. Normally, New Table a mapping table is required to map such kind of relationships.
In this relationship new table is required to store reference of the
both table.
Many2many field definition.
taxes_id = fields.Many2many(comodel_name='account.tax', relation='product_taxes_rel', column1='prod_id', column2='tax_id', string='Customer Taxes')
========================================================================
Actually in this framework we don't need to care about the relational table of M2M, that will be auto managed. So in your case it's not required. And I am not sure why you have created this class, be specific with your requirements. And try to update question with the target you want to achieve.
class ab_site_text_rel(models.Model):
This is not required.

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 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 ;-)

related attributes , related fields on inherited view odoo

what is related attribute , what it can be used for ? and how to add a related attribute .
I'm trying to add a related field for total amount.
Related Field
In such case we need to take the value from any other table but we already have the reference of that table in our model, in that case we can utilize one functionality with that we can add the multiple fields from the reference table by just having the only one reference field in our model.
One relational field (Many2one) of the source model is mandatory to
have in the destination model to create relational field.
Consider the company_currency_id field from the res.currency model is there in the destination model then you can get the current rate of that currency in your target model.
syntax: v7
_columns = {
'current_rate': fields.related('company_currency_id','rate_silent', type='float', relation='res.currency',digits_compute=dp.get_precision( 'Account'), string='Current Rate', readonly=True),
}
Here,
company_currency_id => the field in the same model through which the new field will be relate,
rate_silent => is the field which you are going to relate with new field, means the field from source model,
relation => is the source model name,
type => is the datatype of the source field
Syntax: v8 and newer version
current_rate = fields.Float(string='Current Rate', related='company_currency_id.rate_silent', store=True, readonly=True)
Note :
Value is available in that field only after you save the record.
When you update value in your newly defined related field it
will be updated in source field as well, though it's always advisable
to set readonly in newly defined field.
In context of Odoo related field means, that its value will be
read from another table (related table) --> store=False
read from another table, but stored in the table its defined on --> store=True
Examples (Odoo V8):
sale.order currency_id: it is persisted in product_pricelist
stock_quant packaging_type_id: it is persisted in product_packaging and stock_quant. Everytime you change the value on product_packinging it will be updated on stock_quant, too, not vice versa.
**Related Field* is used when you wanted to pull a value from another model you can use related field on fields.
Here is an example for you.
order_id = fields.Many2one(comodel_name='sale.order', 'Sale Order')
order_amount = fields.Monetary(string='Order Amount',
store=True,
related='order_id.amount_total')
you must add a Many2one field in the model which relates to the model you want to access a field. in our case model is sale.order.
with the related kwarg you can relate field of the related model defined in the Many2one field. in our case order_id.
Setting the store kwarg will automatically store the value in database. With new API the value of the related field will be automatically updated.(Reference)
Hope this helps!

django query multiple tables with foreign key pointing on self

lets say I have a model named User, and other models representing actions done by the a user, like "User_clicked", "User_left", "User_ate_cookie" etc. etc.
the User_* models have different fields and inherit from a single abstract class (User_do_something)
my question is this:
what's the django-way of querying ALL the models, from all the relevant tables, that point on a specific user?
eg. I want to do User.get_all_actions() and get a list with mixed type of models in them, containing all the objects that inherit from User_do_something and point on the specific user.
Note: performance is critical. I don't want to make multiple db queries and combine the list, if possible, I want to do it with a single sql select.
some code to be clear:
class User(models.Model):
uuid = models.UUIDField(unique=True, default=uuid.uuid4)
creation_time = models.DateTimeField(auto_now_add=True)
def get_all_actions(self):
'''
return a list with ALL the actions this player did.
'''
??????? how do I do this query ???????
class User_do_action(models.Model):
user = models.ForeignKey(User)
creation_time = models.DateTimeField(auto_now_add=True)
class Meta:
abstract = True
class User_click(User_do_action):
... some fields
class User_left(User_do_action):
... some fields
class User_ate_cookie(User_do_action):
... some fields
etc. etc.
thanks!

How to create a reference field in OpenERP 6

I am trying to create a field from the web gui of OpenERP and field type as reference
1st there is no better docs about reference
2nd what I want is when someone selects the field it should give another option on selection which is not happening (though it is giving some field but 2nd field throws an error)!
It throws an error object does not exist
Reference fields are mainly used for showing different model's records as reference in your record. For example you have created a model such that whenever a sale order, purchase order, delivery order, project etc are created and saved, then a new record with data like user name, date, some notes should be created in your model. So here you add a reference field which link to the original record(sale order, purchase order etc) from which your record is created. You can find this in res.request model in openerp 6
To create an reference field in your class
def _get_selection_list(self, cr, uid, context=None):
##return a list of tuples. tuples containing model name and name of the record
model_pool = self.pool.get('ir.model')
ids = model_pool.search(cr, uid, [('name','not ilike','.')])
res = model_pool.read(cr, uid, ids, ['model', 'name'])
return [(r['model'], r['name']) for r in res] + [('','')]
_columns = {
'ref': fields.reference(Reference', selection=_get_selection_list, size=128)
}