Skip to Content
Menu
This question has been flagged
2 Replies
5412 Views
I have always the same error:
  File "/usr/lib/python3/dist-packages/odoo/fields.py", line 547, in _setup_related_full
    field = target._fields[name]
KeyError: 'company_id'

 
For me it's all ok

THIS IS MY VIEW:
===============
<odoo>
<data>

<record
id="gcond.view_move_tree" model="ir.ui.view">
<field
name="name">test.move.tree</field>
<field
name="model">test.registra.mm</field>
<field
name="arch" type="xml">
<tree
decoration-info="state == 'draft'" string="Journal Entries">
<field
name="date"/>
<field
name="name"/>
<field
name="partner_id"/>
<field
name="ref"/>
<field
name="journal_id"/>
<field
name="amount" sum="Total Amount"/>
<field
name="state"/>
<field
name="currency_id" invisible="1"/>
</tree>
</field>
</record>

<record
id="gcond.view_form_mm" model="ir.ui.view">
<field
name="name">test.account.reg.form.mm</field>
<field
name="model">test.registra.mm</field>
<field
name="arch" type="xml">
<form
string="Account Entry" duplicate="false">
<header>
<field
name="state" widget="statusbar"/>
</header>
<sheet>
<field
name="id" invisible="1"/>
<div
class="oe_button_box">
</div>
<h1>
<field
name="name" readonly="True" attrs="{'invisible':[('name','=','/')]}"/>
</h1>
<group>
<group>
<field
name="date"/>
</group>
<group>
<field
name="journal_id" options="{'no_open': True, 'no_create': True}"/>
<field
name="company_id"/>
<field
name="amount" invisible="1"/>
<field
name="currency_id" invisible="1"/>

</group>
</group>
<notebook>
<page
string="Journal Items">
<field
name="line_ids" widget="one2many_list"
context="{'line_ids': line_ids, 'journal_id': journal_id }">
<tree
editable="bottom" string="Journal Items">
<field
name="account_id" domain="[('company_id', '=', parent.company_id), ('deprecated', '=', False)]"/>
<field
name="partner_id"
domain="['|', ('parent_id', '=', False), ('is_company', '=', True)]"/>
<field
name="name"/>
<field
name="company_currency_id" invisible="1"/>
<field
name="company_id" domain="[('company_id', '=', parent.company_id)]" invisible="1"/>
<field
name="currency_id" options="{'no_create': True}" />
<field
name="debit" sum="Total Debit"/>
<field
name="credit" sum="Total Credit"/>
</tree>
<!-- Form view to cover mobile use -->
<form>
<group>

</group>
</form>
</field>
</page>
<page
string="Other Info">
<group>

</group>
</page>
</notebook>
</sheet>
</form>
</field>
</record>


<record
id="gcond.view_account_move_filter" model="ir.ui.view">
<field
name="name">test.move.select</field>
<field
name="model">test.registra.mm</field>
<field
name="arch" type="xml">
<search
string="Search Move">
<field
name="name" filter_domain="['|', ('name','ilike',self), ('ref','ilike',self)]" string="Move"/>
<field
name="date"/>
<filter
string="Unposted" name="unposted" domain="[('state','=','draft')]" help="Unposted Journal Entries"/>
<filter
string="Posted" name="posted" domain="[('state','=','posted')]" help="Posted Journal Entries"/>
<separator/>
<filter
string="Sales" name="sales" domain="[('journal_id.type','=','sale')]" context="{'default_journal_type': 'sale'}"/>
<filter
string="Purchases" name="purchases" domain="[('journal_id.type','=','purchase')]" context="{'default_journal_type': 'purchase'}"/>
<filter
string="Bank Operations" name="bankoperations" domain="[('journal_id.type','=','bank')]" context="{'default_journal_type': 'bank'}"/>
<filter
string="Cash Operations" name="cashoperations" domain="[('journal_id.type','=','cash')]" context="{'default_journal_type': 'cash'}"/>
<filter
string="Miscellaneous Operations" domain="[('journal_id.type','=','general')]" name="misc_filter" context="{'default_journal_type': 'general'}"/>
<separator/>
<field
name="partner_id"/>
<field
name="journal_id"/>
<group
expand="0" string="Group By">
<filter
string="Partner" name="partner" domain="[]" context="{'group_by':'partner_id'}"/>
<filter
string="Journal" name="journal" domain="[]" context="{'group_by':'journal_id'}"/>
<filter
string="Status" name="status" domain="[]" context="{'group_by':'state'}"/>
<filter
string="Date" name="date" domain="[]" context="{'group_by':'date'}" help="Journal Entries by Date"/>
</group>
</search>
</field>
</record>

<!-- actions opening views on models -->

<record model="ir.actions.act_window" id="gcond.action_window">
<field
name="name">gcond window</field>
<field
name="res_model">test.registra.mm</field>
<field
name="view_mode">tree,form</field>
</record>

<record
id="gcond.action_move_journal_line" model="ir.actions.act_window">
<field
name="name">Journal Entries</field>
<field
name="res_model">test.registra.mm</field>
<field
name="view_type">form</field>
<field
name="view_mode">tree,form</field>
<field
name="view_id" ref="gcond.view_move_tree"/>
<field
name="search_view_id" ref="gcond.view_account_move_filter"/>
<field
name="context">{'search_default_misc_filter':1, 'view_no_maturity': True}</field>
<field
name="help" type="html">
<p
class="o_view_nocontent_smiling_face">
Create a journal entry
</p><p>
A journal entry consists of several journal items, each of
which is either a debit or a credit transaction.
</p>
</field>
</record>

<menuitem
name="Gcond"
id="gcond.menu_condominio"
web_icon="account,static/description/icon.png"
sequence="40"/>
<!-- Top menu item -->
<!-- menu categories -->

<menuitem name="Millesimi" id="gcond.menu_1" parent="gcond.menu_condominio"/>

<!--
<menuitem name="Menu 2" id="gcond.menu_2" parent="gcond.menu_root"/>
-->
<!-- actions -->

<menuitem name="Lista" id="gcond.menu_1_list" parent="gcond.menu_1" action="gcond.action_window"/>
<!--
<menuitem name="Server to list" id="gcond" parent="gcond.menu_2"
action="gcond.action_server"/>
-->

<menuitem
action="gcond.action_move_journal_line"
id="menu_action_move_journal_line_form"
parent="gcond.menu_condominio"
sequence="1"/>

</data>
</odoo>


THIS IS MY MODEL: ================
<odoo>
<data>

<record
id="gcond.view_move_tree" model="ir.ui.view">
<field
name="name">test.move.tree</field>
<field
name="model">test.registra.mm</field>
<field
name="arch" type="xml">
<tree
decoration-info="state == 'draft'" string="Journal Entries">
<field
name="date"/>
<field
name="name"/>
<field
name="partner_id"/>
<field
name="ref"/>
<field
name="journal_id"/>
<field
name="amount" sum="Total Amount"/>
<field
name="state"/>
<field
name="currency_id" invisible="1"/>
</tree>
</field>
</record>

<record
id="gcond.view_form_mm" model="ir.ui.view">
<field
name="name">test.account.reg.form.mm</field>
<field
name="model">test.registra.mm</field>
<field
name="arch" type="xml">
<form
string="Account Entry" duplicate="false">
<header>
<field
name="state" widget="statusbar"/>
</header>
<sheet>
<field
name="id" invisible="1"/>
<div
class="oe_button_box">
</div>
<h1>
<field
name="name" readonly="True" attrs="{'invisible':[('name','=','/')]}"/>
</h1>
<group>
<group>
<field
name="date"/>
</group>
<group>
<field
name="journal_id" options="{'no_open': True, 'no_create': True}"/>
<field
name="company_id"/>
<field
name="amount" invisible="1"/>
<field
name="currency_id" invisible="1"/>

</group>
</group>
<notebook>
<page
string="Journal Items">
<field
name="line_ids" widget="one2many_list"
context="{'line_ids': line_ids, 'journal_id': journal_id }">
<tree
editable="bottom" string="Journal Items">
<field
name="account_id" domain="[('company_id', '=', parent.company_id), ('deprecated', '=', False)]"/>
<field
name="partner_id"
domain="['|', ('parent_id', '=', False), ('is_company', '=', True)]"/>
<field
name="name"/>
<field
name="company_currency_id" invisible="1"/>
<field
name="company_id" domain="[('company_id', '=', parent.company_id)]" invisible="1"/>
<field
name="currency_id" options="{'no_create': True}" />
<field
name="debit" sum="Total Debit"/>
<field
name="credit" sum="Total Credit"/>
</tree>
<!-- Form view to cover mobile use -->
<form>
<group>

</group>
</form>
</field>
</page>
<page
string="Other Info">
<group>

</group>
</page>
</notebook>
</sheet>
</form>
</field>
</record>


<record
id="gcond.view_account_move_filter" model="ir.ui.view">
<field
name="name">test.move.select</field>
<field
name="model">test.registra.mm</field>
<field
name="arch" type="xml">
<search
string="Search Move">
<field
name="name" filter_domain="['|', ('name','ilike',self), ('ref','ilike',self)]" string="Move"/>
<field
name="date"/>
<filter
string="Unposted" name="unposted" domain="[('state','=','draft')]" help="Unposted Journal Entries"/>
<filter
string="Posted" name="posted" domain="[('state','=','posted')]" help="Posted Journal Entries"/>
<separator/>
<filter
string="Sales" name="sales" domain="[('journal_id.type','=','sale')]" context="{'default_journal_type': 'sale'}"/>
<filter
string="Purchases" name="purchases" domain="[('journal_id.type','=','purchase')]" context="{'default_journal_type': 'purchase'}"/>
<filter
string="Bank Operations" name="bankoperations" domain="[('journal_id.type','=','bank')]" context="{'default_journal_type': 'bank'}"/>
<filter
string="Cash Operations" name="cashoperations" domain="[('journal_id.type','=','cash')]" context="{'default_journal_type': 'cash'}"/>
<filter
string="Miscellaneous Operations" domain="[('journal_id.type','=','general')]" name="misc_filter" context="{'default_journal_type': 'general'}"/>
<separator/>
<field
name="partner_id"/>
<field
name="journal_id"/>
<group
expand="0" string="Group By">
<filter
string="Partner" name="partner" domain="[]" context="{'group_by':'partner_id'}"/>
<filter
string="Journal" name="journal" domain="[]" context="{'group_by':'journal_id'}"/>
<filter
string="Status" name="status" domain="[]" context="{'group_by':'state'}"/>
<filter
string="Date" name="date" domain="[]" context="{'group_by':'date'}" help="Journal Entries by Date"/>
</group>
</search>
</field>
</record>

<!-- actions opening views on models -->

<record model="ir.actions.act_window" id="gcond.action_window">
<field
name="name">gcond window</field>
<field
name="res_model">test.registra.mm</field>
<field
name="view_mode">tree,form</field>
</record>

<record
id="gcond.action_move_journal_line" model="ir.actions.act_window">
<field
name="name">Journal Entries</field>
<field
name="res_model">test.registra.mm</field>
<field
name="view_type">form</field>
<field
name="view_mode">tree,form</field>
<field
name="view_id" ref="gcond.view_move_tree"/>
<field
name="search_view_id" ref="gcond.view_account_move_filter"/>
<field
name="context">{'search_default_misc_filter':1, 'view_no_maturity': True}</field>
<field
name="help" type="html">
<p
class="o_view_nocontent_smiling_face">
Create a journal entry
</p><p>
A journal entry consists of several journal items, each of
which is either a debit or a credit transaction.
</p>
</field>
</record>

<menuitem
name="Gcond"
id="gcond.menu_condominio"
web_icon="account,static/description/icon.png"
sequence="40"/>
<!-- Top menu item -->
<!-- menu categories -->

<menuitem name="Millesimi" id="gcond.menu_1" parent="gcond.menu_condominio"/>

<!--
<menuitem name="Menu 2" id="gcond.menu_2" parent="gcond.menu_root"/>
-->
<!-- actions -->

<menuitem name="Lista" id="gcond.menu_1_list" parent="gcond.menu_1" action="gcond.action_window"/>
<!--
<menuitem name="Server to list" id="gcond" parent="gcond.menu_2"
action="gcond.action_server"/>
-->

<menuitem
action="gcond.action_move_journal_line"
id="menu_action_move_journal_line_form"
parent="gcond.menu_condominio"
sequence="1"/>

</data>
</odoo>
Avatar
Discard
Author
Thank's

Il giorno lun 1 giu 2020 alle ore 23:08 Noura EL ALLAM <nea@odoo.com> ha scritto:

Une nouvelle question Persistent error : " field = target._fields[name] KeyError: 'company_id'" le Aide a été publiée. Cliquez ici pour accéder à la question :

Voir la question


Envoyé par Odoo S.A. using Odoo.

Author Best Answer

SORRY THIS IS THE MODEL

# -*- coding: utf-8 -*-

from copy import deepcopy
import logging
import time
from datetime import date
from collections import OrderedDict, defaultdict
from odoo import api, fields, models, _
from odoo.osv import expression
from odoo.exceptions import RedirectWarning, UserError, ValidationError
from odoo.tools.misc import formatLang, format_date
from odoo.tools import float_is_zero, float_compare
from odoo.tools.safe_eval import safe_eval
from odoo.addons import decimal_precision as dp
from lxml import etree



_logger = logging.getLogger(__name__)


class TestMove(models.Model):
_name = "test.registra.mm"
_description = "Journal Entries mm"
_order = 'date desc, id desc'


@api.multi
def _get_default_journal(self):
#raise UserError("test sul company_id dell'utente (n. %d), questo è il test su 'default_journal_type' : %s" % (self.env.user.company_id.id, self.env.context.get('default_journal_type')))
if self.env.context.get('default_journal_type'):
return self.env['account.journal'].search([('company_id', '=', self.env.user.company_id.id), ('type', '=', self.env.context['default_journal_type'])], limit=1).id

@api.one
@api.depends('company_id')
def _compute_currency(self):
_logger.info("========================================= user -> company (n. %s)" % (str(self.env.user.company_id)))
self.currency_id = self.company_id.currency_id or self.env.user.company_id.currency_id


@api.multi
@api.depends('line_ids.partner_id')
def _compute_partner_id(self):
for move in self:
partner = move.line_ids.mapped('partner_id')
move.partner_id = partner.id if len(partner) == 1 else False



@api.multi
@api.depends('line_ids.debit', 'line_ids.credit')
def _amount_compute(self):
for move in self:
total = 0.0
for line in move.line_ids:
total += line.debit
move.amount = total


name = fields.Char(string='Number', required=True, copy=False, default='/')
ref = fields.Char(string='Reference', copy=False)
date = fields.Date(required=True, index=True, default=fields.Date.context_today)
line_ids = fields.One2many('test.move.line', 'move_id', string='Journal Items', copy=True)
journal_id = fields.Many2one('account.journal', string='Journal', required=True,
states={'posted': [('readonly', True)]},
default=_get_default_journal)
partner_id = fields.Many2one('res.partner', compute='_compute_partner_id', string="Partner", store=True, readonly=True)
amount = fields.Monetary(compute='_amount_compute', store=True)

currency_id = fields.Many2one('res.currency', compute='_compute_currency', store=True, string="Currency")
state = fields.Selection([('draft', 'Unposted'), ('posted', 'Posted')], string='Status',
required=True, readonly=True, copy=False, default='draft',
help='All manually created new journal entries are usually in the status \'Unposted\', '
'but you can set the option to skip that status on the related journal. '
'In that case, they will behave as journal entries automatically created by the '
'system on document validation (invoices, bank statements...) and will be created '
'in \'Posted\' status.')
# qui dovrebbe essereci l'errore: abbiamo il registro (ed anche l'azienda) ma ma non lo vede come secondo livello
company_id = fields.Many2one('res.company', related='journal_id.company_id', string='Company', store=True,
readonly=False)

@api.multi
def assert_balanced(self):
if not self.ids:
return True

# /!\ As this method is called in create / write, we can't make the assumption the computed stored fields
# are already done. Then, this query MUST NOT depend of computed stored fields (e.g. balance).
# It happens as the ORM makes the create with the 'no_recompute' statement.
self._cr.execute('''
SELECT line.move_id, ROUND(SUM(line.debit - line.credit), currency.decimal_places)
FROM test_move_line line
JOIN test_registra_mm move ON move.id = line.move_id
JOIN account_journal journal ON journal.id = move.journal_id
JOIN res_company company ON company.id = journal.company_id
JOIN res_currency currency ON currency.id = company.currency_id
WHERE line.move_id IN %s
GROUP BY line.move_id, currency.decimal_places
HAVING ROUND(SUM(line.debit - line.credit), currency.decimal_places) != 0.0;
''', [tuple(self.ids)])

res = self._cr.fetchone()
if res:
raise UserError(
_("Cannot create unbalanced journal entry.") +
"\n\n{}{}".format(_('Difference debit - credit: '), res[1])
)
return True

@api.model
def create(self, vals):
move = super(TestMove,
self.with_context(check_move_validity=False, partner_id=vals.get('partner_id'))).create(vals)
_logger.info("===================================================")
_logger.info("\n\n{}{}".format(_('funzione create: '), str(vals)))
move.assert_balanced()
return move

@api.multi
def write(self, vals):
if 'line_ids' in vals:
res = super(TestMove, self.with_context(check_move_validity=False)).write(vals)
self.assert_balanced()
else:
res = super(TestMove, self).write(vals)
_logger.info("========================================= risultato (n. %s)" % (str(vals)))
return res




class TestMoveLine(models.Model):
_name = "test.move.line"
_description = "Dettaglio registrazione millesimi"
_order = "date desc, id desc"

@api.model
def _get_currency(self):
currency = False
context = self._context or {}
if context.get('default_journal_id', False):
currency = self.env['account.journal'].browse(context['default_journal_id']).currency_id
return currency

@api.model
def _debug_contexet(self):
contesto = dict(self.env.context)
_logger.info("================" + str(contesto))

name = fields.Char(string="Label")

company_currency_id = fields.Many2one('res.currency', related='company_id.currency_id', string="Company Currency",
readonly=True,
help='Utility field to express amount currency', store=True)
currency_id = fields.Many2one('res.currency', string='Currency', default=_get_currency, help="The optional other currency if it is a multi-currency entry.")

account_id = fields.Many2one('account.account', string='Account', required=True, index=True,
ondelete='restrict', domain=[('deprecated', '=', True)],
default=lambda self: self._context.get('account_id', False))
move_id = fields.Many2one('test.registra.mm', string='Journal Entry', ondelete="cascade", help="The move of this entry line.", index=True, required=True, auto_join=True)
debit = fields.Monetary(default=0.0, currency_field='company_currency_id')
credit = fields.Monetary(default=0.0, currency_field='company_currency_id')
balance = fields.Monetary(store=True, currency_field='company_currency_id', help="Technical field holding the debit - credit in order to open meaningful graph views from reports")

journal_id = fields.Many2one('account.journal', related='move_id.journal_id', string='Journal', readonly=False,
index=True, store=True, copy=False) # related is required

date = fields.Date(related='move_id.date', string='Date', index=True, store=True, copy=False,
readonly=False) # related is required
partner_id = fields.Many2one('res.partner', string='Partner', ondelete='restrict')
company_id = fields.Many2one('res.company', related='account_id.company_id', string='Company', store=True,
readonly=True)

@api.model
def _query_get(self, domain=None):

self.check_access_rights('read')

context = dict(self._context or {})
_logger.info("========================================= contesto query (n. %s)" % (str(context)))

domain = domain or []
if not isinstance(domain, (list, tuple)):
domain = safe_eval(domain)

date_field = 'date'
if context.get('aged_balance'):
date_field = 'date_maturity'
if context.get('date_to'):
domain += [(date_field, '<=', context['date_to'])]
if context.get('date_from'):
if not context.get('strict_range'):
domain += ['|', (date_field, '>=', context['date_from']),
('account_id.user_type_id.include_initial_balance', '=', True)]
elif context.get('initial_bal'):
domain += [(date_field, '<', context['date_from'])]
else:
domain += [(date_field, '>=', context['date_from'])]

if context.get('journal_ids'):
domain += [('journal_id', 'in', context['journal_ids'])]

state = context.get('state')
if state and state.lower() != 'all':
domain += [('move_id.state', '=', state)]

if context.get('company_id'):
domain += [('company_id', '=', context['company_id'])]

if 'company_ids' in context:
domain += [('company_id', 'in', context['company_ids'])]

if context.get('reconcile_date'):
domain += ['|', ('reconciled', '=', False), '|',
('matched_debit_ids.max_date', '>', context['reconcile_date']),
('matched_credit_ids.max_date', '>', context['reconcile_date'])]

if context.get('account_tag_ids'):
domain += [('account_id.tag_ids', 'in', context['account_tag_ids'].ids)]

if context.get('account_ids'):
domain += [('account_id', 'in', context['account_ids'].ids)]

if context.get('analytic_tag_ids'):
domain += [('analytic_tag_ids', 'in', context['analytic_tag_ids'].ids)]

if context.get('analytic_account_ids'):
domain += [('analytic_account_id', 'in', context['analytic_account_ids'].ids)]

if context.get('partner_ids'):
domain += [('partner_id', 'in', context['partner_ids'].ids)]

if context.get('partner_categories'):
domain += [('partner_id.category_id', 'in', context['partner_categories'].ids)]

where_clause = ""
where_clause_params = []
tables = ''
if domain:
query = self._where_calc(domain)

# Wrap the query with 'company_id IN (...)' to avoid bypassing company access rights.
self._apply_ir_rules(query)

tables, where_clause, where_clause_params = query.get_sql()
return tables, where_clause, where_clause_params
Avatar
Discard