Skip to Content
Odoo Menú
  • Registra entrada
  • Prova-ho gratis
  • Aplicacions
    Finances
    • Comptabilitat
    • Facturació
    • Despeses
    • Full de càlcul (IA)
    • Documents
    • Signatura
    Vendes
    • CRM
    • Vendes
    • Punt de venda per a botigues
    • Punt de venda per a restaurants
    • Subscripcions
    • Lloguer
    Imatges de llocs web
    • Creació de llocs web
    • Comerç electrònic
    • Blog
    • Fòrum
    • Xat en directe
    • Aprenentatge en línia
    Cadena de subministrament
    • Inventari
    • Fabricació
    • PLM
    • Compres
    • Manteniment
    • Qualitat
    Recursos humans
    • Empleats
    • Reclutament
    • Absències
    • Avaluacions
    • Recomanacions
    • Flota
    Màrqueting
    • Màrqueting Social
    • Màrqueting per correu electrònic
    • Màrqueting per SMS
    • Esdeveniments
    • Automatització del màrqueting
    • Enquestes
    Serveis
    • Projectes
    • Fulls d'hores
    • Servei de camp
    • Suport
    • Planificació
    • Cites
    Productivitat
    • Converses
    • Validacions
    • IoT
    • VoIP
    • Coneixements
    • WhatsApp
    Aplicacions de tercers Odoo Studio Plataforma d'Odoo al núvol
  • Sectors
    Comerç al detall
    • Llibreria
    • Botiga de roba
    • Botiga de mobles
    • Botiga d'ultramarins
    • Ferreteria
    • Botiga de joguines
    Food & Hospitality
    • Bar i pub
    • Restaurant
    • Menjar ràpid
    • Guest House
    • Distribuïdor de begudes
    • Hotel
    Immobiliari
    • Agència immobiliària
    • Estudi d'arquitectura
    • Construcció
    • Gestió immobiliària
    • Jardineria
    • Associació de propietaris de béns immobles
    Consultoria
    • Empresa comptable
    • Partner d'Odoo
    • Agència de màrqueting
    • Bufet d'advocats
    • Captació de talent
    • Auditoria i certificació
    Fabricació
    • Textile
    • Metal
    • Mobles
    • Menjar
    • Brewery
    • Regals corporatius
    Salut i fitness
    • Club d'esport
    • Òptica
    • Centre de fitness
    • Especialistes en benestar
    • Farmàcia
    • Perruqueria
    Trades
    • Servei de manteniment
    • Hardware i suport informàtic
    • Sistemes d'energia solar
    • Shoe Maker
    • Serveis de neteja
    • Instal·lacions HVAC
    Altres
    • Nonprofit Organization
    • Agència del medi ambient
    • Lloguer de panells publicitaris
    • Fotografia
    • Lloguer de bicicletes
    • Distribuïdors de programari
    Browse all Industries
  • Comunitat
    Aprèn
    • Tutorials
    • Documentació
    • Certificacions
    • Formació
    • Blog
    • Pòdcast
    Potenciar l'educació
    • Programa educatiu
    • Scale-Up! El joc empresarial
    • Visita Odoo
    Obtindre el programari
    • Descarregar
    • Comparar edicions
    • Novetats de les versions
    Col·laborar
    • GitHub
    • Fòrum
    • Esdeveniments
    • Traduccions
    • Converteix-te en partner
    • Services for Partners
    • Registra la teva empresa comptable
    Obtindre els serveis
    • Troba un partner
    • Troba un comptable
    • Contacta amb un expert
    • Serveis d'implementació
    • Referències del client
    • Suport
    • Actualitzacions
    Github Youtube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Programar una demo
  • Preus
  • Ajuda

Odoo is the world's easiest all-in-one management software.
It includes hundreds of business apps:

  • CRM
  • e-Commerce
  • Comptabilitat
  • Inventari
  • PoS
  • Projectes
  • MRP
All apps
You need to be registered to interact with the community.
All Posts People Badges
Etiquetes (View all)
odoo accounting v14 pos v15
About this forum
You need to be registered to interact with the community.
All Posts People Badges
Etiquetes (View all)
odoo accounting v14 pos v15
About this forum
Ajuda

what I should put in the search([ ]) to match date in different model/database?

Subscriure's

Get notified when there's activity on this post

This question has been flagged
searchcontextcalculation
6 Respostes
8775 Vistes
Avatar
David Yao

Hi all, Thanks for you guys help, I have some overall understanding on using @api.depends do the calculation. But I still have some questions on this.

Here is my code:  

    class costSummary(models.Model):

        _name = 'cost.summary'

        total = XXXXX

        cost_line = fields.One2many('cost.details', inverse_name='cost_id')

        @api.depends('cost_line.cost_line_cost')

        def _compute_amount_my(self):

            for rec in self:

            cost_rec = rec.env['hr.expense.line'].search([('cost_id', '=', id)])

            rec.total = sum(cost_rec.mapped('cost_line_cost'))

    class costDetails(models.Model):

        _name = 'cost.details'

        cost_id = fields.Many2one('cost.summary', ondelete='cascade')

        cost_line_id = fields.Char(string="SubExpense")

        cost_line_desc = fields.Text(string="SubExpense Description")

        cost_line_cost = fields.Float(string='Cost')


 what make me confusing is that, inside the search([ ]), what I should put to make cost_id and  cost_line match up?  I have tried  search([('cost_id', '=', id)]),  search([('cost_id', '=', cost_line)])... none of them work. why I using id is because id is the name in the database.

Can anyone please show me what I missed? any hint will be useful, Thanks a lot!

0
Avatar
Descartar
Avatar
Samo Arko
Best Answer

this key error happens when you try to use parent or child values in api.depends or api.onchange, because you can't change related models in real time, but only fields from the current model. The value will change only when you'll save. I made a mine to work so that I overwritten my write and create methods and in them I get the values from the related models and compute the fields that way. 

When working with onchange/depends think of it as working on a object and not the data in the DB. It's a bit weird that the id is a new id object but, this is just how it works. You can't even go trough ids... "for child in self.child_ids:"

@api.model
def create(self, vals):
    record = super(ModelName, self).create(vals)
    self.refresh_values()
    return record

  I'll get all the values and compute them in the self.refresh_values() method. In the method you can search for records with the code from the previous post or if you have them related its easier to go through relations. 

0
Avatar
Descartar
Avatar
Niyas Raphy (Walnut Software Solutions)
Best Answer

Hi,


Change this line like this,

cost_rec = rec.env['cost.details'].search([('cost_id', '=', rec.id)])


Thanks

0
Avatar
Descartar
David Yao
Autor

even it does't showing error message, the calculation is not working, the value/result becomes 0. BTW, I tried doing this --- search([('cost_id', '=', 20)]) --- and it works fine (20 is what I find in database, it representing the id of that record)

David Yao
Autor

Hi, I tried to use search([('expense_id', '=', 'rec.cost_line.cost_id')]), then it gives me following error message.

This is log information:

Traceback (most recent call last):

File "C:\Users\...\odoo\odoo\fields.py", line 936, in __get__

value = record.env.cache.get(record, self)

File "C:\Users\...\odoo\odoo\api.py", line 960, in get

value = self._data[field][record.id][key]

KeyError: <odoo.api.Environment object at 0x0000000009E30908>

During handling of the above exception, another exception occurred:

Traceback (most recent call last):

File "C:\Users\...\odoo\odoo\http.py", line 647, in _handle_exception

return super(JsonRequest, self)._handle_exception(exception)

File "C:\Users\...\odoo\odoo\http.py", line 307, in _handle_exception

raise pycompat.reraise(type(exception), exception, sys.exc_info()[2])

File "C:\Users\...\odoo\odoo\tools\pycompat.py", line 87, in reraise

raise value

File "C:\Users\...\odoo\odoo\http.py", line 689, in dispatch

result = self._call_function(**self.params)

File "C:\Users\...\odoo\odoo\http.py", line 339, in _call_function

return checked_call(self.db, *args, **kwargs)

File "C:\Users\...\odoo\odoo\service\model.py", line 97, in wrapper

return f(dbname, *args, **kwargs)

File "C:\Users\...\odoo\odoo\http.py", line 332, in checked_call

result = self.endpoint(*a, **kw)

File "C:\Users\...\odoo\odoo\http.py", line 933, in __call__

return self.method(*args, **kw)

File "C:\Users\...\odoo\odoo\http.py", line 512, in response_wrap

response = f(*args, **kw)

File "C:\Users\...\odoo\addons\web\controllers\main.py", line 930, in call_kw

return self._call_kw(model, method, args, kwargs)

File "C:\Users\...\odoo\addons\web\controllers\main.py", line 922, in _call_kw

return call_kw(request.env[model], method, args, kwargs)

File "C:\Users\...\odoo\odoo\api.py", line 689, in call_kw

return call_kw_multi(method, model, args, kwargs)

File "C:\Users\...\odoo\odoo\api.py", line 680, in call_kw_multi

result = method(recs, *args, **kwargs)

File "C:\Users\...\odoo\odoo\models.py", line 5015, in onchange

record.mapped(dotname)

File "C:\Users\...\odoo\odoo\models.py", line 4429, in mapped

recs = recs._mapped_func(operator.itemgetter(name))

File "C:\Users\...\odoo\odoo\models.py", line 4408, in _mapped_func

vals = [func(rec) for rec in self]

File "C:\Users\...\odoo\odoo\models.py", line 4408, in <listcomp>

vals = [func(rec) for rec in self]

File "C:\Users\...\odoo\odoo\models.py", line 4675, in __getitem__

return self._fields[key].__get__(self, type(self))

File "C:\Users\...\odoo\odoo\fields.py", line 942, in __get__

self.determine_draft_value(record)

File "C:\Users\...\odoo\odoo\fields.py", line 1062, in determine_draft_value

self._compute_value(record)

File "C:\Users\...\odoo\odoo\fields.py", line 998, in _compute_value

getattr(records, self.compute)()

File "C:\Users\...\odoo\addons\hr_expense\models\hr_expense.py", line 94, in _compute_amount_my

print("show me", rec.expense_line.expense_id)

File "C:\Users\...\odoo\odoo\fields.py", line 934, in __get__

record.ensure_one()

File "C:\Users\...\odoo\odoo\models.py", line 4283, in ensure_one

raise ValueError("Expected singleton: %s" % self)

ValueError: Expected singleton: hr.expense.line(9, 10, 11, <odoo.models.NewId object at 0x000000000888C0D8>)

Niyas Raphy (Walnut Software Solutions)

cost_rec = rec.env['cost.details'].search([('cost_id', '=', rec.id)])

David Yao
Autor

emmm....anything changed in your second code/answer?

Enjoying the discussion? Don't just read, join in!

Create an account today to enjoy exclusive features and engage with our awesome community!

Registrar-se
Related Posts Respostes Vistes Activitat
Search options are not getting refined. (Coding problem)
search context
Avatar
0
de març 15
3976
context.get not working in xml search filter domain Solved
search context domain_filter
Avatar
1
de maig 16
10182
Context: function never called - need help
python search context
Avatar
0
de maig 15
3724
many2one search context
many2one search context
Avatar
Avatar
2
de març 15
8519
How do I filter a spreadsheet pivot to the current/previous month
search
Avatar
Avatar
1
de jul. 25
1489
Community
  • Tutorials
  • Documentació
  • Fòrum
Codi obert
  • Descarregar
  • GitHub
  • Runbot
  • Traduccions
Serveis
  • Allotjament a Odoo.sh
  • Suport
  • Actualització
  • Desenvolupaments personalitzats
  • Educació
  • Troba un comptable
  • Troba un partner
  • Converteix-te en partner
Sobre nosaltres
  • La nostra empresa
  • Actius de marca
  • Contacta amb nosaltres
  • Llocs de treball
  • Esdeveniments
  • Pòdcast
  • Blog
  • Clients
  • Informació legal • Privacitat
  • Seguretat
الْعَرَبيّة Català 简体中文 繁體中文 (台灣) Čeština Dansk Nederlands English Suomi Français Deutsch हिंदी Bahasa Indonesia Italiano 日本語 한국어 (KR) Lietuvių kalba Język polski Português (BR) română русский язык Slovenský jazyk slovenščina Español (América Latina) Español ภาษาไทย Türkçe українська Tiếng Việt

Odoo és un conjunt d'aplicacions empresarials de codi obert que cobreix totes les necessitats de la teva empresa: CRM, comerç electrònic, comptabilitat, inventari, punt de venda, gestió de projectes, etc.

La proposta única de valor d'Odoo és ser molt fàcil d'utilitzar i estar totalment integrat, ambdues alhora.

Website made with

Odoo Experience on YouTube

1. Use the live chat to ask your questions.
2. The operator answers within a few minutes.

Live support on Youtube
Watch now