This question has been flagged
2 Replies
8678 Views

How to format mapped() result?

mapped() output like ['name1','name2','name3'] and related float field [100, 200, 300]

would like to add that value to fields.Text so that it goes fields.Text: name1, name2, name3

and also add currency like $100, $200, $300

can this be done? any example?

thank you

Avatar
Discard
Author Best Answer

okey i'm partly solve:
This is my custom modules
that have this fields

report = fields.Many2many(comodel_name="my.report", string="Report")
tprod = fields.Text(string="Product", compute="_tprod")
tprice = fields.Text(string="Prices", compute="_tprice")
tcost = fields.Text(string="Cost", compute="_tcost")


@api.multi
@api.depends('report')
def _tprod(self):
        for rec in self:
            rec.tprod = str(rec.report.mapped('name')).strip("[]").strip("''")

this result is: name1', 'name2
expected : name1, name2 - with out ( ' )

@api.multi
@api.depends('report')
    def _tprice(self):
        for rec in self:
            rec.tprice = str(rec.report.mapped(lambda record: '$ ' + str(record.price))).strip("[]")

this result is : '$100', '$200'
expected: $100, $200
if i put .strip("[]").strip("''") then the result would like $100', '$200 which is not good to look at 

tcost the same as tprice

so for all of you who does not know, mapped() is a list so you cannot add .replace or .strip without turning it to str first that's why must convert str(rec.report.mapped('name')) and also record.price is Float for my part and have to change that as well to str(record.price)

if anyone have more solution to finalize my code please, thank you

Solved with:

@api.multi
@api.depends('report')
def _tprod(self):
        for rec in self:
            rec.tprod = str(rec.report.mapped('name')).strip("[]").replace("'", "")

or if it's not working, you can do this:

    rec.tprod = str(rec.report.mapped('name')).strip("[]")
    rec.tprod = rec.tprod.replace("'", "")

anyway other tips is if you use store=True then you have to delete the value first or if there is already a value in your field, then either delete the value or delete it from database (just be cautions if you are deleting from database, always have backups), or maybe just use "@api.onchange" for testing.

My problem was using store=True i did not see the .replace() because it's already saved values in database (was testing using @api.depends thought that it will change just by refreshing), choose hard way delete field from postgresql and upgrade my module - but you can also create new field and delete old ones

Avatar
Discard
Best Answer

When you use `mapped`, it is going to result in a list. Afterwards, you can use standard Python to manage how you want to format that list. This isn't the prettiest example, but you can do something like this:


>>> ", ".join(["${}".format(price) for price in ['100', '200']])
'$100, $200'


Avatar
Discard