error with rec.env['book.tickets'].search() - odoo

#api.depends('totalbook')
def _computebook(self):
sum_a = 0
for rec in self:
for l in rec.env['book.tickets'].search([('status', 'in', ('sold', 'rent'))]):
if l:
sum_a += 1
rec.currentbook = rec.totalbook - sum_a
I use this compute to calculate current book in library.
But when I run this code, the problem calculate of my each book base on all books.

When you are write any compute method in odoo, in self you will get all the list of browsable objects.
And then you are trying to search data from that browsable object. That's why you get a error.
You have to use self.env instead of rec.env.
Because you can't search data from browsable object you can access only data of that browsable object.
You have to add limit 1 on when you are searching a record of multiple record are than you will get another expected Singleton error.
Either you can you use another loop after searching record.
Let me know if you face any errors again.
Thanks

this error occured because
whenever you are trying to make a object of another model at that time you should have to use with self.env instead of rec.env because in your method rec is just a record-set of your instance
so please update your method as per the following snippet.
for l in self.env['book.tickets'].search([('status', 'in', ('sold','rent'))]):

Related

Expected singleton odoo 9

After enter 2 and more new row in tree view and click on save get error
raise ValueError("Expected singleton: %s" % self)
ValueError: Expected singleton: my.model(2116, 2117)
My source code:
#api.depends('start', 'finish','stop')
def total_fun(self):
time1 = datetime.strptime(self.start, "%Y-%m-%d %H:%M:%S")
time2 = datetime.strptime(self.finish, "%Y-%m-%d %H:%M:%S")
self.total = round(((time2 - time1).seconds / float(60*60) - self.stop))
Error message says -> expected singleton this means: you are using recordset instead of record.
To fix this use
for rec in self:
in the begining of function, and then use rec instead of self
As you can see in the error message Expected singleton: my.model(2116, 2117)
By default in odoo the self is always a recordSet (means it can contain more then one record.) so when you do self.getSomeField here odoo will be confused wich record you want to get the value from.
if you don't tell odoo that make sure that the self will always contain one record when you acces an attribute if the recordSet contains more than one record this error is raised.
Now how to tell odoo make sure there is always one record is by adding #api.one decorator to the method. but is not recommended because odoo in your case there is two record so he will loop and call the method for each record and pass a recordSet that have only that record. imagine that you execute a search or any communication with database.
so don't use #api.one only if you are sure of what you are doing because you can make 10000 method call and interact with database.
like this example using #api.one:
# every call to this method you will execute a search.
self.env['some.model'].search([('m2o_id' , '=', self.id)]
you can do this before the loop:
# one query for all record with one call to the method
result = self.env['some.model'].search([('m2o_id' , 'in', self.ids)]
for rec in self:
# use result here
# or here ..

Computed many2many field dependencies in Odoo 10

I am trying to create a new field on the sale.order.line model. This field is called x_all_route_ids, and is meant to contain all of the available stock.location.route for an Order Line.
It should look up the product_id.route_ids and product_id.routes_from_categ_ids for the Order Line, and join them together into a single set of Routes.
I am trying to set this field up through the Odoo UI, but getting error related to my "Dependencies".
I have Dependencies defined as:
product_id, product_id.route_ids, product_id.routes_from_categ_ids
I have Compute defined as:
for record in self:
record['x_all_route_ids'] = record.product_id.route_ids
To start I am just trying to get the field to show the same value as product_id.route_ids, but it's not working. When I save, I get the following error:
Error while validating constraint
Unknown field u'product_id' in dependency u'product_id'
Any idea what I'm doing wrong here?
I was able to get this working. I think the issue was just a bug in the UI that came about because I had been trying so many different things. After refreshing the page, the following worked:
Dependency = product_id
Field type = many2many
Compute method:
for record in self:
full = record.product_id.route_ids | record.product_id.route_from_categ_ids
record['x_all_route_ids'] = full.filtered('sale_selectable')

Odoo - Understanding recordsets in the new api

Please look at the following code block:
class hr_payslip:
...
#api.multi # same behavior with or without method decorators
def do_something(self):
print "self------------------------------->",self
for r in self:
print "r------------------------------->",r
As you can see I'm overriding a 'hr.payslip' model and I need to access some field inside this method. The problem is that it doesn't make sense to me what gets printed:
self-------------------------------> hr.payslip(hr.payslip(1,),)
r-------------------------------> hr.payslip(hr.payslip(1,),)
Why is it the same thing inside and outside of for loop. If it's always a 'recordset', how would one access one record's field.
My lack of understanding is probably connected to this question also:
Odoo - Cannot loop trough model records
Working on RecordSets always means working on RecordSets. When you loop over one RecordSet you will get RecordSets as looping variable. But you can only access fields directly when the length of a RecordSet is 1 or 0. You can test it fairly easy (more then one payslip in database!):
slips = self.env['hr.payslip'].search([])
# Exception because you cannot access the field directly on multi entries
print slips.id
# Working
print slips.ids
for slip in slips:
print slip.id

How to do math operation with columns on grouped rows

I have Event model with following attributes (I quoted only problem related attributes), this model is filled periodically by API call, calling external service (Google Calendar):
colorid: number # (0-11)
event_start: datetime
event_end: datetime
I need to count duration of grouped events, grouped by colorid. I have Event instance method to calculate single event duration:
def event_duration
((event_end.to_datetime - event_start.to_datetime) * 24 * 60 ).to_i
end
Now, I need to do something like this:
event = Event.group(:colorid).sum(event_duration)
But this doesnot work for me, as long as I get error that event_duration column doesnot exists. My idea is to add one more attribute to Event model "event_duration", and count and update this attribute during Event record creation, in this case I would have column called "event_duration", and I might be ale to use sum on this attribute. But I am not sure this is good and "system solution", as long as I would like to have model data reflecting "raw" received data from API call, and do all math and statistics on the top of model data.
event_duration is instance method (not column name). error was raised because Event.sum only calculates the sum of certain column
on your case, I think it would be easier to use enumerable methods
duration_by_color_id = {}
grouped_events = Event.all.group_by(&:colorid)
grouped_events.each do |colorid, events|
duration_by_color_id[colorid] = events.collect(&:event_duration).sum
end
Source :
Enumerable's group_by
Enumerable's collect

Sap Code Inspector - Generating a table of all PCodes linked to the classes

I have problems to read the error codes and corresponding messages of SCI message classes.
Is there an way to easy access those?
I'm using "Praxishandbuch SAP Code Inspector" as a reference, but in that regard it is of no help.
I looked in Se11 but the information to the messages isn't helpful.
Has someone an approch to build such a table?
You can try this, perhaps it will work for you. I use the code below to get the access to all the errors found by Code Inspector for particular user(s):
data: ref_inspec_a type ref to cl_ci_inspection.
ref_inspec_a = cl_ci_inspection=>get_ref(
p_user = pa_iuser
p_name = pa_inam
p_vers = pa_ivers ).
data: ls_resp type scir_resp,
lt_resp type scit_resp.
clear: ls_resp, lt_resp.
ls_resp-sign = 'I'.
ls_resp-option = 'EQ'.
ls_resp-low = pa_fuser.
insert ls_resp into table lt_resp.
call method ref_inspec_a->get_results
exporting
p_responsibl = lt_resp
exceptions
insp_not_yet_executed = 1
overflow = 2
others = 3.
Playing around with LT_RESP you can get results for more users at the same time.
After you execute the code above, you can check the attributes SCIRESTPS and SCIRESTHD of the object REF_INSPEC_A. These are the large tables, which contain the result data of the SCI check. You can either work with them on your own, or you can simply pass the object REF_INSPEC_A into the function module SCI_SHOW_RESULTS to get regular SCI user interface.
I found out that you can get all the changeable messages (found in SCI GoTo/Management Of/ Message Priorities) can be read from the scimessages attribute of the test classes.
With this help you can get about 60% of all errors.