Se rendre au contenu
Odoo Menu
  • Se connecter
  • Essai gratuit
  • Applications
    Finance
    • Comptabilité
    • Facturation
    • Notes de frais
    • Feuilles de calcul (BI)
    • Documents
    • Signature
    Ventes
    • CRM
    • Ventes
    • PdV Boutique
    • PdV Restaurant
    • Abonnements
    • Location
    Sites web
    • Site Web
    • eCommerce
    • Blog
    • Forum
    • Live Chat
    • eLearning
    Chaîne d'approvisionnement
    • Inventaire
    • Fabrication
    • PLM
    • Achats
    • Maintenance
    • Qualité
    Ressources Humaines
    • Employés
    • Recrutement
    • Congés
    • Évaluations
    • Recommandations
    • Parc automobile
    Marketing
    • Marketing Social
    • E-mail Marketing
    • SMS Marketing
    • Événements
    • Marketing Automation
    • Sondages
    Services
    • Projet
    • Feuilles de temps
    • Services sur Site
    • Assistance
    • Planification
    • Rendez-vous
    Productivité
    • Discussion
    • Validations
    • Internet des Objets
    • VoIP
    • Connaissances
    • WhatsApp
    Applications tierces Odoo Studio Plateforme Cloud d'Odoo
  • Industries
    Commerce de détail
    • Librairie
    • Magasin de vêtements
    • Magasin de meubles
    • Épicerie
    • Quincaillerie
    • Magasin de jouets
    Food & Hospitality
    • Bar et Pub
    • Restaurant
    • Fast-food
    • Maison d’hôtes
    • Distributeur de boissons
    • Hôtel
    Immobilier
    • Agence immobilière
    • Cabinet d'architecture
    • Construction
    • Gestion immobilière
    • Jardinage
    • Association de copropriétaires
    Consultance
    • Cabinet d'expertise comptable
    • Partenaire Odoo
    • Agence Marketing
    • Cabinet d'avocats
    • Aquisition de talents
    • Audit & Certification
    Fabrication
    • Textile
    • Métal
    • Meubles
    • Alimentation
    • Brewery
    • Cadeaux d'entreprise
    Santé & Fitness
    • Club de sports
    • Opticien
    • Salle de fitness
    • Praticiens bien-être
    • Pharmacie
    • Salon de coiffure
    Trades
    • Bricoleur
    • Matériel informatique et support
    • Systèmes photovoltaïques
    • Cordonnier
    • Services de nettoyage
    • Services CVC
    Autres
    • Organisation à but non lucratif
    • Agence environnementale
    • Location de panneaux d'affichage
    • Photographie
    • Leasing de vélos
    • Revendeur de logiciel
    Browse all Industries
  • Communauté
    Apprenez
    • Tutoriels
    • Documentation
    • Certifications
    • Formation
    • Blog
    • Podcast
    Renforcer l'éducation
    • Programme éducatif
    • Business Game Scale-Up!
    • Rendez-nous visite
    Obtenir le logiciel
    • Téléchargement
    • Comparez les éditions
    • Versions
    Collaborer
    • Github
    • Forum
    • Événements
    • Traductions
    • Devenez partenaire
    • Services for Partners
    • Enregistrer votre cabinet comptable
    Nos Services
    • Trouver un partenaire
    • Trouver un comptable
    • Rencontrer un conseiller
    • Services de mise en œuvre
    • Références clients
    • Assistance
    • Mises à niveau
    Github Youtube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Obtenir une démonstration
  • Tarification
  • Aide

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

  • CRM
  • e-Commerce
  • Comptabilité
  • Inventaire
  • PoS
  • Projet
  • MRP
All apps
Vous devez être inscrit pour interagir avec la communauté.
Toutes les publications Personnes Badges
Étiquettes (Voir toutl)
odoo accounting v14 pos v15
À propos de ce forum
Vous devez être inscrit pour interagir avec la communauté.
Toutes les publications Personnes Badges
Étiquettes (Voir toutl)
odoo accounting v14 pos v15
À propos de ce forum
Aide

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

S'inscrire

Recevez une notification lorsqu'il y a de l'activité sur ce poste

Cette question a été signalée
searchcontextcalculation
6 Réponses
8773 Vues
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
Ignorer
Avatar
Samo Arko
Meilleure réponse

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
Ignorer
Avatar
Niyas Raphy (Walnut Software Solutions)
Meilleure réponse

Hi,


Change this line like this,

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


Thanks

0
Avatar
Ignorer
David Yao
Auteur

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
Auteur

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
Auteur

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

Vous appréciez la discussion ? Ne vous contentez pas de lire, rejoignez-nous !

Créez un compte dès aujourd'hui pour profiter de fonctionnalités exclusives et échanger avec notre formidable communauté !

S'inscrire
Publications associées Réponses Vues Activité
Search options are not getting refined. (Coding problem)
search context
Avatar
0
mars 15
3976
context.get not working in xml search filter domain Résolu
search context domain_filter
Avatar
1
mai 16
10182
Context: function never called - need help
python search context
Avatar
0
mai 15
3723
many2one search context
many2one search context
Avatar
Avatar
2
mars 15
8519
How do I filter a spreadsheet pivot to the current/previous month
search
Avatar
Avatar
1
juil. 25
1489
Communauté
  • Tutoriels
  • Documentation
  • Forum
Open Source
  • Téléchargement
  • Github
  • Runbot
  • Traductions
Services
  • Hébergement Odoo.sh
  • Assistance
  • Migration
  • Développements personnalisés
  • Éducation
  • Trouver un comptable
  • Trouver un partenaire
  • Devenez partenaire
À propos
  • Notre société
  • Actifs de la marque
  • Contactez-nous
  • Emplois
  • Événements
  • Podcast
  • Blog
  • Clients
  • Informations légales • Confidentialité
  • Sécurité.
الْعَرَبيّة 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 est une suite d'applications open source couvrant tous les besoins de votre entreprise : CRM, eCommerce, Comptabilité, Inventaire, Point de Vente, Gestion de Projet, etc.

Le positionnement unique d'Odoo est d'être à la fois très facile à utiliser et totalement intégré.

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