Перейти к содержимому
Odoo Меню
  • Войти
  • Попробовать бесплатно
  • Модули
    Финансы
    • Бухгалтерия
    • Выставление счетов
    • Расходы
    • Таблицы
    • Документооборот
    • Подпись
    Продажи
    • CRM
    • Продажи
    • POS Магазин
    • POS Ресторан
    • Подписки
    • Аренда
    Вебсайты
    • Конструктор вебсайтов
    • eCommerce
    • Блог
    • Форум
    • Онлайн-чат
    • Электронное обучение
    Логистика
    • Склад
    • Производство
    • PLM
    • Закупки
    • Обслуживание
    • Качество
    Отдел кадров
    • Сотрудники
    • Подбор персонала
    • Отпуска
    • Оценка персонала
    • Реферальная программа
    • Автопарк
    Маркетинг
    • SMM
    • E-mail рассылки
    • СМС рассылки
    • Мероприятия
    • Автоматизация маркетинга
    • Опросы
    Услуги
    • Проекты
    • Табели
    • Выездной сервис
    • Поддержка
    • Планирование
    • Встречи
    Продуктивность
    • Обсуждения
    • Согласование
    • IoT
    • VoIP-телефония
    • Knowledge
    • WhatsApp
    Сторонние приложения Модуль Студия Odoo Платформа Odoo Cloud
  • Индустрии
    Розничная торговля
    • Книжный магазин
    • Магазин одежды
    • Мебельный магазин
    • Продуктовый магазин
    • Строительный магазин
    • Магазин игрушек
    Гостинично-ресторанный бизнес
    • Бар и паб
    • Ресторан
    • Фастфуд
    • Гостевой дом
    • Дистрибьютор напитков
    • Отель
    Недвижимость
    • Агентство недвижимости
    • Архитектурное бюро
    • Строительство
    • Управление недвижимостью
    • Ландшафтный дизайн
    • Товарищество собственников жилья
    Консалтинг
    • Бухгалтерская фирма
    • Партнер Odoo
    • Маркетинговое агентство
    • Юридическая фирма
    • Подбор персонала
    • Аудиторское бюро
    Производство
    • Текстиль
    • Металл
    • Мебель
    • Продукты питания
    • Пивоварня
    • Корпоративные сувениры
    Здоровье и фитнес
    • Спортивный комплекс
    • Магазин оптики
    • Фитнес-клуб
    • Велнес-центр
    • Аптека
    • Салон красоты
    Услуги
    • Специалист по бытовым услугам
    • Продажа и обслуживание IT-оборудования
    • Солнечные энергосистемы
    • Производство обуви
    • Клининг
    • Системы ОВКВ
    Прочее
    • Некоммерческая организация
    • Консалтинг в сфере устойчивого развития
    • Аренда рекламных щитов
    • Бизнес по фотосъемке
    • Прокат велосипедов
    • Реселлер программного обеспечения
    Все индустрии
  • Community
    Обучение
    • Видео уроки
    • Документация
    • Сертификация
    • Тренинг
    • Блог
    • Подкаст
    Образование и развитие
    • Образовательная программа
    • Деловая игра Scale Up!
    • Экскурсия в офис Odoo
    ПО
    • Скачать
    • Сравнить версии
    • Релизы
    Сотрудничество
    • Github
    • Форум
    • Мероприятия
    • Перевод
    • Стать партнером
    • Услуги для партнеров
    • Зарегистрировать бухгалтерскую фирму
    Услуги
    • Найти партнера
    • Найти бухгалтера
    • Встреча с экспертом
    • Услуги по внедрению
    • Отзывы клиентов
    • Поддержка
    • Обновления
    Github Youtube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Заказать демонстрацию
  • Цены
  • Поддержка

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

  • CRM
  • e-Commerce
  • Бухгалтерия
  • Склад
  • PoS
  • Проекты
  • MRP
All apps
Чтобы взаимодействовать с сообществом, необходимо зарегистрироваться.
Все посты Люди Значки
Теги (Смотреть все)
odoo accounting v14 pos v15
Об этом форуме
Чтобы взаимодействовать с сообществом, необходимо зарегистрироваться.
Все посты Люди Значки
Теги (Смотреть все)
odoo accounting v14 pos v15
Об этом форуме
Помощь

v14: how can i get parent value in the creation of child?

Подписаться

Получайте уведомления о появлении активности в этом посте

Этот вопрос был отмечен
parentchildv14
2 Ответы
6849 Представления
Аватар
SmithJohn45

model is 'product.category ', want to inhereit and add a field 'level' to add the levels to find which level record i want.

we knew that by default (as recommended) that first entry 'All' here should present to start the parent child relations.

when user create a new category and select All as its parent, we knew that its level is 1 and we can add 2, programatically it should be parent level + 1 ... so we can add levels of any depth.

i don't know how to code it, so please help me for the below onchange function (or any other better approach, please specify), modify it to achieve what i wants to have.

@api.onchange(parent_id):

def _onchange_parent_id(self):

  find the level of parent here...

  self.level = parent_level + 1

regards


0
Аватар
Отменить
Аватар
Neha Sharma
Лучший ответ

Hello SmithJohn45,

Suppose we have a product category hierarchy as below


A > B > C > D


and we need to find the level for the category "C" with the code (the answer is 3)

So to find the level for the category, here is the method that you need to write:


def find_level_of_category(self, catg_id):

    level = 1

    if catg_id.parent_id:

        parent_id = catg_id.parent_id

        while (parent_id):

            level += 1

            parent_id = parent_id.parent_id

        return level

    return level



You can simply call this method to your onchange, you need to pass "self.parent_id" as a parameter into the above method, so it will give you the level of the "self.parent_id".


Thanks!

For more information Contact us:- https://kanakinfosystems.com/odoo-development-services

0
Аватар
Отменить
SmithJohn45
Автор

thank you @Neha Sharma for help :), will implement and give feedback here.

SmithJohn45
Автор

@Neha Sharma, please check, if it is ok or i made mistake(s)

from odoo import api, fields, models

class ProductCateg(models.Model):

_inherit = 'product.category'

level = fields.Integer(string='Level')

@api.onchange('parent_id')

def find_level_of_category(self):

levels = 1

if self.parent_id:

parent_id = self.parent_id

while (parent_id):

levels += 1

parent_id = parent_id.parent_id

self.level = levels

regards

Neha Sharma

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

from odoo import api, fields, models

class ProductCateg(models.Model):

_inherit = 'product.category'

level = fields.Integer(string='Level')

@api.onchange('parent_id')

def onchange_parent_id(self):

if self.parent_id:

level = self.find_level_of_category()

self.level = level

def find_level_of_category(self):

level = 1

if self.parent_id:

parent_id = self.parent_id

while (parent_id):

level += 1

parent_id = parent_id.parent_id

return level

return level

SmithJohn45
Автор

@Neha Sharma, implemented the code for model, updated manually level column for All to 1 and All / Electronics to 2, from UI created a record, choose All / Electronics as its parent, but level not updated with required value. ( i have copy/pasted your last code as it is, indent with pycharm option and restart server, upgraded module and then checked ) anything else i missed ?

Neha Sharma

Can you share a screenshot of your pycharm code?

SmithJohn45
Автор

can't post screenshot here, so i have to use Answer portion here...

SmithJohn45
Автор

@Neha Sharma, i have added screenshot, please check.

Neha Sharma
Okay I will attach .py and xml file and video or flow maybe it helps you


On Fri, 29 Jan 2021 at 15:47, SmithJohn45 <oralover2006@gmail.com> wrote:

@Neha Sharma, i have added screenshot, please check.

Sent by Odoo S.A. using Odoo.

Neha Sharma

i have sent a mail to you with attached .py and xml file along with video maybe it works

SmithJohn45
Автор

thanks @Neha Sharma for your struggle to help me, i have seen in my gmail account for your email but not yet received, also checked in Spam, may be sometimes take time, will check after 15 minutes. thanks again :)

Neha Sharma
Ok, no problem. 

On Fri, 29 Jan 2021 at 18:15, SmithJohn45 <oralover2006@gmail.com> wrote:

thanks @Neha Sharma for your struggle to help me, i have seen in my gmail account for your email but not yet received, also checked in Spam, may be sometimes take time, will check after 15 minutes. thanks again :)

Sent by Odoo S.A. using Odoo.

Neha Sharma
Have you received my mail?

On Fri, 29 Jan, 2021, 6:15 PM SmithJohn45, <oralover2006@gmail.com> wrote:

thanks @Neha Sharma for your struggle to help me, i have seen in my gmail account for your email but not yet received, also checked in Spam, may be sometimes take time, will check after 15 minutes. thanks again :)

Sent by Odoo S.A. using Odoo.

SmithJohn45
Автор

@Neha Sharm, no, not yet received email, don't know why, even checked Spam and also Trash may be i accidently deleted but failed to find the email. what is the Subject of email? and is it through Odoo platform?

how i can request a feature in forum, there is no notification here within forum if someone Answer or Comment... user should check the email or On email's notification, but it is not possible for us especially when we are on Client.

Neha Sharma
okay, I will be sent you a mail again with some attachments of the .py and XML file and video flow.


On Sat, 30 Jan 2021 at 09:22, SmithJohn45 <oralover2006@gmail.com> wrote:

@Neha Sharm, no, not yet received email, don't know why, even checked Spam and also Trash may be i accidently deleted but failed to find the email. what is the Subject of email? and is it through Odoo platform?

how i can request a feature in forum, there is no notification here within forum if someone Answer or Comment... user should check the email or On email's notification, but it is not possible for us especially when we are on Client.

Sent by Odoo S.A. using Odoo.

Neha Sharma
I already sent you mail again if you find it then please reply to my mail.
Thanks...

On Mon, 1 Feb 2021 at 16:34, Neha Sharma <nsa@kanakinfosystems.com> wrote:
okay, I will be sent you a mail again with some attachments of the .py and XML file and video flow.


On Sat, 30 Jan 2021 at 09:22, SmithJohn45 <oralover2006@gmail.com> wrote:

@Neha Sharm, no, not yet received email, don't know why, even checked Spam and also Trash may be i accidently deleted but failed to find the email. what is the Subject of email? and is it through Odoo platform?

how i can request a feature in forum, there is no notification here within forum if someone Answer or Comment... user should check the email or On email's notification, but it is not possible for us especially when we are on Client.

Sent by Odoo S.A. using Odoo.

Аватар
SmithJohn45
Автор Лучший ответ

@Neha Sharma, screenshot is here as instructed. (already mentioned in my opening post that "i don't now how to code it" so, it is copy pasted as you did it for me)


0
Аватар
Отменить
Julian Dumitrascu

Where did you paste it?

Не оставайтесь в стороне – присоединяйтесь к обсуждению!

Создайте аккаунт сегодня, чтобы получить доступ к эксклюзивным функциям и стать частью нашего замечательного сообщества!

Регистрация
Похожие посты Ответы Просмотры Активность
ver 14: how to search parent_id and its all child in model product.category in Many2one field
domain parent child v14
Аватар
Аватар
1
июл. 23
6292
How to add child view field in Parent search view
parent child
Аватар
Аватар
1
мар. 15
8465
Odoo Project oddities and limitations
project task parent child
Аватар
Аватар
1
апр. 24
2474
How to create Workcenter childs?
tree workcenter child v14
Аватар
0
нояб. 21
2604
How do i get a parent model in a child model?
models parent model child
Аватар
0
мая 17
4815
Сообщество
  • Видео уроки
  • Документация
  • Форум
Открытый исходный код
  • Скачать
  • Github
  • Runbot
  • Перевод
Услуги
  • Хостинг Odoo.sh
  • Поддержка
  • Обновление
  • Индивидуальные решения по доработке
  • Образование
  • Найти бухгалтера
  • Найти партнера
  • Стать партнером
О нас
  • Наша компания
  • Активы бренда
  • Cвяжитесь с нами
  • Вакансии
  • Мероприятия
  • Подкаст
  • Блог
  • Клиенты
  • Правовые документы • Конфиденциальность
  • Безопасность
الْعَرَبيّة 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 – это набор бизнес-модулей с открытым исходным кодом, который закроет все потребности вашей компании: CRM, E-commerce, Бухгалтерия, Склад, POS, управление проектами и др.

Odoo сочетает в себе простоту использования и полную интеграцию всех бизнес-процессов в одной системе.

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