How to correct filter fields domain in a model? - odoo

I'm getting the following error trying to filter a field by another field value of the same model.
File
"/opt/..../tfutbol/models/partido.py",
line 29, in Partido
figura = fields.Many2one('tfutbol.jugador',domain=[('equipo_id','=',local.id)])
RuntimeError: maximum recursion depth exceeded while calling a Python
object
The line of code trying with the problem is:
figura = fields.Many2one('tfutbol.jugador',domain=[('equipo_id','=',local.id),('equipo_id','=',visitante.id)])
All the relevant code, is above:
class Partido(models.Model):
_name = 'tfutbol.partido'
local = fields.Many2one('tfutbol.equipo')
visitante = fields.Many2one('tfutbol.equipo')
figura = fields.Many2one('tfutbol.jugador',domain=[('equipo_id','=',local.id),('equipo_id','=',visitante.id)])
class Equipo(models.Model):
_name = 'tfutbol.equipo'
name = fields.Char('Nombre')
jugador_ids = fields.One2many('tfutbol.jugador', 'equipo_id', string="Jugadores")
class Jugador(models.Model):
_name = 'tfutbol.jugador'
name = fields.Char('Nombre')
equipo_id = fields.Many2one('tfutbol.equipo')
Thanks for reading!

If you read the docstring on /odoo/fields.py on the Many2one class definition you will see that:
:param domain: an optional domain to set on candidate values on the
client side (domain or string)
That means that you cannot use the dot notation (record.field) to pull in values because this has not been implemented on javascript.
So what you can do to dynamically create a domain like the one you want is:
Create an onchange method that will be invoked every time you set a value on the local and visitante fields and will change the domain on the figura field. For example:
#api.onchange('figura','visitante')
def onchange_method(self):
domain = {}
domain['figura'] = [('equipo_id','=',self.local.id),('equipo_id','=',self.visitante.id)]
return {'domain': domain}
Note: When you do not set an operator in a domain with multiple leafs (parameters) an explicit AND is added, so in your domain you are searching for the equipo_id filed to be equal to self.local.id AND self.visitante.id which will not work, you might want to add an OR like:
['|',('equipo_id','=',self.local.id),('equipo_id','=',self.visitante.id)]

Related

Odoo: Override Integer field in onchange not working whereas Float is changed - WHY?

I have extended the product.template with following fields:
length = fields.Integer("Length", default=0)
length_float = fields.Float("Float", default=0.0)
Additionally I have extended the product.packaging model with this fields and an onchange method:
product_id_ref = fields.Many2one('product.product', string="Product Reference")
length = fields.Integer('Length')
length_float = fields.Float('Length_Float')
#api.onchange("product_id_ref")
def _onchange_product(self):
if self.product_id_ref:
self.length_float = self.product_id_ref.length_float
self.length = self.product_id_ref.length
Interestingly the FLOAT field length_float is changed as expected and shown in the view. The INTEGER field is not changed.
Something more suprising is that if I change the order of the onchange method
#api.onchange("product_id_ref")
def _onchange_product(self):
if self.product_id_ref:
self.length = self.product_id_ref.length
self.length_float = self.product_id_ref.length_float
NO value is changed!
How could that be?? Does anyone have an idea?
Thanks!
It came out that the problem was the 'length' field itself. This name leads to problems on the javascript side. Renaming leads to the desired result.

Question about when to use lua colon syntax

local Public = {}
function Public.new(ent)
local State = {}
function State:update(player)
ent:setLinearVelocity(0,0)
end
function State:start(player)
ent.fixedRotation = true
self.attackTimer = _G.m.addTimer(200, function()
ent:setState('attacking', player)
end)
end
function State:exit(player)
ent.fixedRotation = false
timer.cancel(self.attackTimer)
end
return State
end
return Public
I'm using a linter and its complaining that I'm using the colon unnecessarily for my update and exit methods. The reason I do this is to keep all my methods uniform. Sometimes I need self and sometimes I don't.
But in general is there any advantage to using colon on these at all? It seems like if i have something like State:start then I could just reference State directly. I could do State.attackTimer vs self.attackTimer..
Why would you ever really need the colon? If you have access to the table that holds the method then you have access to self.. right?
The : syntax is a great tool when you are making a class using a table and a metatable.
Your code above, rather then creating a class, creates an encapsulated set of functions. which have access to State as an upvalue.
I will use this class from Lua Users - SimpleLuaClasses as an example:
Account = {}
Account.__index = Account
function Account:create(balance)
local acnt = {} -- our new object
setmetatable(acnt,Account) -- make Account handle lookup
acnt.balance = balance -- initialize our object
return acnt
end
function Account:withdraw(amount)
self.balance = self.balance - amount
end
-- create and use an Account
acc = Account:create(1000)
acc:withdraw(100)
Here we have an instance(acc) of the Account class. To adjust or modify the values in this specific instance of Account we can not refer to Account.balance inside of Account:withdraw. We need a reference to the table where the data is stored, and that is where passing that table using : comes in.
acc:withdraw(100) is just syntactic sugar for acc.withdraw(acc, 100) passing in our table as the first param self. When you define Account:withdraw(amount) there is an implicate first variable self the definition could be written as Account.withdraw(self, amount)

Return elements in SQLAlchemy AppenderBaseQuery object to Flask-WTForm field

I am working on the "edit" functionality for a form. When the form is rendered, the fields should populate with data that is stored in the database. One of this field is returned as a SQlAlchemy AppenderBaseQuery object. This causes a query statement to be pre-populated in the field, instead of the results of the query.
How do I pre-populate the form with elements in the object instead?
form = MyForm(obj=MyObject)
if form.validate_on_submit():
form.populate_obj(MyObject)
The field is defined as a StringField.
Note:
I am passing MyObject to pre-populate the form because there is a thing with WTForm where form.Field.data does not get updated at all.
form = MyForm()
form.Field.data = "test" #Pre-populate Field with "test"
if validate_on_submit():
MyObject.Field = Form.Field.data #Assign data in Field to MyObject
#...
My Object.Field will not be updated with the new Form.Field.data, not sure why.
As suggested by n-Holmes in the comments:
# Do not initiate the form with object
form = MyForm()
# Split logic to 'GET' and 'POST request'
if request.method == 'GET'
MyForm.Field.Data = ', '.join([element.attribute for element in MyForm.Field.all()]
# MyForm.Field is an AppenderBaseQuery Object >> Returns a query statement
# MyForm.Field.all() returns a list of Objects
# The list comprehension returns a list of a specific attribute for each object
# The .join combines the list to a string, separated by ", "
# This entire thing is pre-populated onto the form
# Eg: "Attribute01, Attribute02, Attribute03"
if validate_on_submit:
MyObject.Field = FunctionToUpdateField(form.Field.data)
# form.Field.data will be a string
# FunctionToUpdateField compares above string with what is stored in db ...
# determines which elements to add / remove

Perl 6 multi methods never match expected signature

I have a class with two multi methods (multi submit).
I call my multi like this:
$perspective.submit(:message($message.content));
Which gets shipped off to my class:
my $perspective-api = API::Perspective.new(:api-key(%*ENV<PERSPECTIVE_API_KEY>));
proto method submit (|) {*}
multi method submit(Str :$message!, MODEL :#models = TOXICITY) {
my $score = $perspective-api.analyze(:#models, :comment($message));
say #models Z=> $score<attributeScores>{#models}.map: *<summaryScore><value>;
multi method submit(Str :$name!, MODEL :#models = TOXICITY) {
my $score = $perspective-api.analyze(:#models, :comment($name));
say #models Z=> $score<attributeScores>{#models}.map: *<summaryScore><value>;
}
However I always get the following response:
Died because of the exception:
Cannot resolve caller AUTOGEN(Rose::ContentAnalysis::Perspective:D: :message(Str)); none of these signatures match:
(Rose::ContentAnalysis::Perspective: Str :$message!, MODEL :#models = MODEL::TOXICITY, *%_)
(Rose::ContentAnalysis::Perspective: Str :$name!, MODEL :#models = MODEL::TOXICITY, *%_)
Despite my named argument (:message) being a Str as required and #models having a default declared.
Multiple dispatch works in two phases:
Considering the number of positional parameters and their types
If there are any where clauses, named parameters, or sub-signatures, doing a test bind of the signature to see if it would match
The second phase will reject the candidate if it fails to bind for any reason. One such reason, and I believe the cause of the issue here, is that the default value is wrongly typed. For example, in:
multi m(:#x = "not-an-array") { }
m()
We get an error:
Cannot resolve caller m(...); none of these signatures match:
(:#x = "not-an-array")
in block <unit> at -e line 1
But changing it to:
multi m(:#x = ["an-array"]) { }
m()
Works fine. (Note that while a default value uses =, it's actually a binding, not an assignment.)
In the case in the question there's this:
MODEL :#models = TOXICITY
Looking at the module source the code is taken from, I see:
enum MODEL is export (
<TOXICITY SEVERE_TOXICITY TOXICITY_FAST IDENTITY_ATTACK
INSULT PROFANITY SEXUALLY_EXPLICIT THREAT FLIRTATION
ATTACK_ON_AUTHOR ATTACK_ON_COMMENTER INCOHERENT INFLAMMATORY
LIKELY_TO_REJECT OBSCENE SPAM UNSUBSTANTIAL>
);
Thus TOXICITY is just an Int, but what's expected is a typed array of MODEL values.
Thus, if you do this:
multi method submit(Str :$message!, MODEL :#models = Array[MODEL](TOXICITY)) {
It should work.
I see two issues.
One is that you have two methods that are identical except for the name of one named parameter.
Named parameters can have aliases:
# V--------------V
multi method submit(Str :name(:$message)!, MODEL :#models = TOXICITY) {
my $score = $perspective-api.analyze(:#models, :comment($message));
say #models Z=> $score<attributeScores>{#models}.map: *<summaryScore><value>;
}
Note that :$message is really short for :message($message)
Now on the problem which actually prevents your code from working.
#models is a Positional, but you are assigning it a singular value in the signature.
Assign it a Positional, and it works:
(In this case it has to be of type Array[MODEL] because of the MODEL type declaration.)
# V---------------------V
multi method submit(Str :name(:$message)!, MODEL :#models = Array[MODEL](TOXICITY,)) {
my $score = $perspective-api.analyze(:#models, :comment($message));
say #models Z=> $score<attributeScores>{#models}.map: *<summaryScore><value>;
}

Odoo: Access field by it's name (given as string)

I have a model, where I want to access a field, given by a string. Example:
def test(self):
field = 'name'
name = getattr(self, field)
This works fine - name is set to self.name. But then I want to access a related field:
def test2(self):
field = 'partner_id.name'
name = getattr(self, field)
That doesn't work (because 'partner_id.name' does not exist on self). Any idea how to do it right?
getattr doesn't support the dot notation, only simple attribute names. You can however create a simple function that does:
def getfield(model, field_name):
value = model
for part in field_name.split('.'):
value = getattr(value, part)
return value
You would use it like this:
def test2(self):
field = 'partner_id.name'
name = getfield(self, field)
You need to use the object that contain partner_id.name
def test2(self):
field = 'name'
object = self.pool.get('res.partner').browse(cr, uid, self.partner_id.id)#v7
#object = self.env['res.partner'].browse(self.partner_id.id)#v8
name = getattr(object, field)
I also came across another solution, inspired by the mail template system:
from openerp.tools.safe_eval import safe_eval as eval
def test2(self):
field = 'partner_id.name'
field = 'object.' + field
name = eval(field, {'object': self})