How to create a reference field in OpenERP 6 - odoo

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

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 add unique Item Code every product in open erp

I'm adding a new product to the open erp. However, I'm unable to add a unique number to each product. But there should be a unique product number for every product.
You can use #api.constrains decorator.
#api.one
#api.constrains('code')
def _unique_code(self):
if len(self.search([('code', '=', self.code)])) > 1:
raise ValidationError("Product code must be unique!")
Id is the always unique for all model in openerp.
And another way,
you can also add your custome field for unique number usind "_sql_constraints"
eg: _sql_constraints = [
('seq_uniq', 'unique (item_code)', _("The Item Code must be \
unique per Stage!"))]

How to send multiple values in many2many field in odoo?

I am trying to generate purchase order from manufacturing order.I have created many2many field for getting multiple products.I want to send multiple product ids to my custom function.I am able to send 1 value but sending more than one gives error as Expected singleton: product.template(4, 3).
from openerp import models,fields,api
class generate_purchase_order(models.Model):
_name = 'mrp_to_purchase_order'
product_id = fields.Many2many('product.template',string='Products',required=True)
#api.multi
def generate_purchase_order2(self):
for wizard in self:
mrp_obj = self.env['mrp.production']
mrp_obj.generate_purchase_order(wizard.product_id.id) #function call
return { 'type': 'ir.actions.act_window_close'}
mrp_custom.py,
from openerp import models,api
class mrp_production(models.Model):
_inherit = 'mrp.production'
#api.multi
def generate_purchase_order(self,product_id):
purchase_line_obj = self.env['purchase.order.line']
context = self._context
for order in self.browse(context['active_ids']):
for line in order.bom_id.bom_line_ids:
if line.product_id.id != product_id:#problem line
continue
#rest of code
singleton: product.template(4, 3)
This error means that code is expecting single record not recordset, so you must change code to allow recordset using or make ensureone with try-catch and avoid errors. Thats general information.
Now if you want to get multiple records from many2many its not problem at all, you must pass this many2many object only and then work with it.
After getting many2many object to work with every record from this recordset you must use for record in recordset:
Also wizard.product_id.id this is error!!! product_id is many2many so you must pass product_id or if you want to browse by yourself you must pass product_id.ids

working of openerp-create & write orm methods

can anyone explain the working of create and write orm mehods in openerp ? Actually I'm stuck at this methods,I'm not getting how it works internally and how can I implement it over a simple program.
class dumval(osv.osv):
_name = 'dum_val'
_columns={
'state':fields.selection([('done','confirm'),('cancel','cancelled')],'position',readonly=True),
'name':fields.char('Name',size=40,required=True,states={'done':[('required','False')]}),
'lname':fields.char('Last name',size=40,required=True),
'fname':fields.char('Full name',size=80,readonly=True),
'addr':fields.char('Address',size=40,required=True,help='enter address'),
}
_defaults = {
'state':'done',
}
It would be nice if u could explain using this example..
A couple of comments plus a bit more detail.
As Lukasz answered, convention is to use periods in your model names dum.val. Usually something like my_module.my_model to ensure there are no name collisions (e.g. account.invoice, sale.order)
I am not sure if your conditional "required" in the model will work; this kind of thing is usually done in the view but it would be worth seeing how the field is defined in the SQL schema.
The create method creates new records (SQL Insert). It takes a dict of values, applies any defaults you have specified and then inserts the record and returns the new ID. Note that you can do compound creates, i.e. if you are creating and invoice, you can add the invoice lines into the dictionary and do it all in one create and OpenERP will take care of the related fields for you (ref write method in https://doc.openerp.com/trunk/server/api_models/)
The write method updates existing records (SQL Update). It takes a dict of values and applies to all of the ids you pass. This is an important point, if you pass a list of ids, the values will be written to all ids. If you want to update a single record, pass a list of one entry, if you want to do different updates to the records, you have to do multiple write calls. You can also manage related fields with a write.
It's convention to give _name like dum.val instead of dum_val.
In dumval class you can write a method:
def abc(cr, uid, ids, context=None):
create_dict = {'name':'xxx','lname':'xxx','fname':'xxx','addr':'xyz'}
# create new object and get id
new_id = self.create(cr, uid, write_dict, context=context)
# write on new object
self.write(cr, uid, new_id, {'lname':'yyy'}, context=context)
For more details look: https://www.openerp.com/files/memento/older_versions/OpenERP_Technical_Memento_v0.6.1.pdf

Openerp 7 many2one dropdown should display field of related record

If you install Openerp 7 with recruitment module. And create a simple entry with following values e.g.
Subject (internal field name = 'name') = 10 Year Experience
Applicant Name = Jhon Smith
Then if you create a custom module with following columns
_columns = {
'applicant_id': fields.many2one('hr.applicant', 'Applicant', required=True),
}
The view widget by default will show a drop-down with the Subject (internal field name ='name') field but i want to show applicant name (internal field name='partner_name') field in drop down, when creating a new record in my custom module.
In Summary how can I display Applicant's Name instead of Subject in drop-down widget in my custom module.
In openerp there is a function called name_get().This function returns a list of tuples containing ID of the record and name tobe displayed. So override this function and return list of tuples containing ID of the record and applicant name
You need to define applicant_id in _rec_name in your custom module.
Try this:
_rec_name = 'applicant_id'
Have a look at Predefined fields.