Skip to Content
Odoo Меню
  • Увійти
  • Спробуйте це безкоштовно
  • Додатки
    Фінанси
    • Бухоблік
    • Виставлення рахунку
    • Витрати
    • Електронні таблиці (BI)
    • Документи
    • Підпис
    Продажі
    • CRM
    • Продажі
    • POS Магазин
    • POS Ресторан
    • Підписки
    • Оренда
    Веб-сайти
    • Конструктор веб-сайту
    • Електронна комерція
    • Блог
    • Форум
    • Живий чат
    • Електронне навчання
    Ланцюг поставок
    • Склад
    • Виробництво
    • PLM
    • Купівлі
    • Технічне обслуговування
    • Якість
    Кадри
    • Співробітники
    • Рекрутинг
    • Відпустки
    • Оцінювання
    • Рекомендації
    • Автотранспорт
    Маркетинг
    • Маркетинг соцмереж
    • Email-маркетинг
    • SMS-маркетинг
    • Події
    • Автом. маркетингу
    • Опитування
    Послуги
    • Проект
    • Табелі
    • Виїзне обслуговування
    • Служба підтримки
    • Планування
    • Призначення
    Продуктивність
    • Обговорення
    • Схвалення
    • IoT
    • IP-телефонія
    • База знань
    • WhatsApp
    Сторонні модулі Odoo Studio Платформа Odoo Cloud
  • Сфери
    Роздрібна торгівля
    • Книжковий магазин
    • Магазин одягу
    • Магазин меблів
    • Продуктовий магазин
    • Магазин будівельних матеріалів
    • Магазин іграшок
    Food & Hospitality
    • Бар та паб
    • Ресторан
    • Фастфуд
    • Guest House
    • Дистриб'ютор напоїв
    • Hotel
    Нерухомість
    • Real Estate Agency
    • Архітектурна фірма
    • Будівництво
    • Управління нерухомістю
    • Садівництво
    • Асоціація власників нерухомості
    Консалтинг
    • Бухгалтерська компанія
    • Партнер Odoo
    • Агенція маркетингу
    • Юридична фірма
    • Придбання Талантів
    • Аудит та сертифікація
    Виробництво
    • Textile
    • Metal
    • Меблі
    • Їжа
    • Brewery
    • Корпоративні подарунки
    Здоров'я & Фітнес
    • Спортивний клуб
    • Оптика
    • Фітнес-центр
    • Практики здоров'я
    • Аптека
    • Салон краси
    Trades
    • Ремонтник
    • IT-обладнання та Підтримка
    • Системи сонячної енергії
    • Shoe Maker
    • Cleaning Services
    • HVAC Services
    Інші
    • Nonprofit Organization
    • Екологічна агенція
    • Оренда білбордів
    • Фотографія
    • Лізинг велосипедів
    • Реселлер програмного забезпечення
    Browse all Industries
  • Спільнота
    Навчання
    • Навчальний посібник
    • Документація
    • Сертифікації
    • Тренування
    • Блог
    • Подкаст
    Сприяйте Освіті
    • Програма навчання
    • Бізнес гра Scale Up!
    • Відвідайте Odoo
    Отримайте програмне забезпечення
    • Завантаження
    • Порівняйте версії
    • Релізи
    Співпрацюйте
    • Github
    • Форум
    • Події
    • Переклади
    • Стати партнером
    • Services for Partners
    • Зареєструйте вашу бухгалтерську фірму
    Отримайте послуги
    • Знайдіть партнера
    • Знайдіть бухгалтера
    • Зустріньтеся з консультантом
    • Послуги з впровадження
    • Референси клієнтів
    • Підтримка
    • Оновлення
    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
Вам необхідно зареєструватися, щоб взаємодіяти зі спільнотою.
All Posts Люди Значки
Мітки (View all)
odoo accounting v14 pos v15
Про цей форум
Вам необхідно зареєструватися, щоб взаємодіяти зі спільнотою.
All Posts Люди Значки
Мітки (View all)
odoo accounting v14 pos v15
Про цей форум
Допомога

[odoo 8 ] : How to update value of one2many field with at second level by using create and write method using API?

Підписатися

Отримуйте сповіщення про активність щодо цієї публікації

Це запитання позначене
one2manycreateupdatewriteodooV8
6 Відповіді
64804 Переглядів
Аватар
Prince Caspion

Hello All,

I've asked this Question again, because i was not able to EDIT my question.

I'm having problem on overriding create method.

I've one2many field in my current model, I want to update the value of that field when new record created, and this one2many field's co-model has it's own one2many fields.

So, basically there is two levels of one2many fields.

My one2many field has one2many field, I want to create record for that model as well,

How can i achieve this?

Any help on this appreciated.

This is need to be done using api coding standard.

EDIT

E.g.

Class A(models.Model):    
_name = 'main.model'
x_ids = fields.one2Many('sub.model','main_id',"Test")

   

Class B(models.Model)    
_name = 'sub.model'   
main_id = fields.Many2one('main.model', "Main Model")
#remaining fields.
xx_ids = fields.One2many('another.sub.model','sub_model_id',"Test")
Class C(models.Model)    
_name = 'another.submodel'
sub_model_id = fields.Many2one('sub.model',"Sub Model")
#remaining fields..go here   

Consider this is model structure, now when i create record of Class A model, I want to updated one2many field of Class B and Class B is having Class C one2many field, so how to update the values or create records with 2 level of one2many field? is there any option?

I am looking for the solution for both side create and write method. Please anyone has idea than it will be really helpful.

Regards,

Prince

2
Аватар
Відмінити
Аватар
Deepa Venkatesh
Найкраща відповідь

You can achieve that in 2 ways:

Case 1: Default Values

if you have fixed data, then you can set default values in both objects i.e in ClassA set default values for 'x_ids' and in ClassB set default values for 'xx_ids'

Case 2: Create/Write method

In the First object (ClassA): while creating itself you can add its lines using One2Many and/or Many2Many semantics.


According to your sample object hierarchy:


@api.model

def create(self, vals):

valsC = {....} # dict of values needed for creating ClassC

valsB = {
'xx_ids': [(0, 0, valsC)],

          ....} # dict of values needed for creating ClassB

vals['x_ids'] = [(0, 0, valsB)] # appending it into the values of ClassA

return super(A, self).create(vals)



In Odoo, at the time of creating a record, you can pass values to its child be it a One2Many or Many2Many by using its semantics, here [(0,0,{})] represents am trying to create new One2Many record.

Note:

In valsB, I have appended the values of ClassC, and this dict am appending the original Vals of Class A, which will be like passing nested dict of values into ClassA

Similarly there exists a semantics for editing/updating, deleting and so, please refer the below samples which are used for both One2Many & Many2Many.


(0, 0, { values }) link to a new record that needs to be created with the given values dictionary

(1, ID, { values }) update the linked record with id = ID (write values on it)

(2, ID) remove and delete the linked record with id = ID (calls unlink on ID, that will delete the object completely, and the link to it as well)

(3, ID) cut the link to the linked record with id = ID (delete the relationship between the two objects but does not delete the target object itself)

(4, ID) link to existing record with id = ID (adds a relationship)

(5) unlink all (like using (3,ID) for all linked records)

(6, 0, [IDs]) replace the list of linked IDs (like using (5) then (4,ID) for each ID in the list of IDs)

7
Аватар
Відмінити
Аватар
Kirubanidhi Rajarathinam
Найкраща відповідь

Update  A SAMPLE one2many record in odoo9, 

search_var = self.browse(self.id)

search_var.update({

'stud_ids': [(0,_, {

'reg_no':4200,

'dob': '04/01/1992',

'stud_name':'amuthan',

})]

})

1
Аватар
Відмінити
Аватар
Qutechs, Ahmed M.Elmubarak
Найкраща відповідь

Hello,

In creation you need to override the create method of class A to be something as:

@api.model

def create(self, vals):

res = super(A, self).create(vals)

#creating C record

c_res = self.env['another.submodel'].create({'field_name': value, ...})

#creating B record

b_res = self.env['sub.model'].create({'field_name': value, ...})

#Adding C to B

b_res.xx_ids += c_res

#Adding B to A [it is also a One2many]

res.x_ids += b_res

return res

You can do similar thing in the write method with some modifications ...


Hope this could helps ...

0
Аватар
Відмінити
Prince Caspion
Автор

@Ahmed: Thanks for the nice example, i will try and check it.

Prince Caspion
Автор

Ahmed given solution does not work , gives me this error, defaults.update(values)

ValueError: dictionary update sequence element #0 has length 3; 2 is required

Qutechs, Ahmed M.Elmubarak

Hi, can you share your code some where ?

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

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

Реєстрація
Related Posts Відповіді Переглядів Дія
Best way to create one2many records in backend
one2many create update
Аватар
0
лист. 22
4967
how to override create or write method Вирішено
one2many create write
Аватар
Аватар
Аватар
3
лип. 17
12679
update one2many field
function one2many create update
Аватар
0
квіт. 19
4294
[odoo 8]: How set value of one2many field by overriding create method with api coding standard? Вирішено
one2many create api override odooV8
Аватар
Аватар
2
груд. 20
9201
how to update odoo One2many field from list of dictionaries?
one2many create update loop dictionary
Аватар
Аватар
3
лип. 20
18765
Спільнота
  • Навчальний посібник
  • Документація
  • Форум
Open Source
  • Завантаження
  • Github
  • Runbot
  • Переклади
Послуги
  • Хостинг Odoo.sh
  • Підтримка
  • Оновлення
  • Кастомні доробки
  • Навчання
  • Знайдіть бухгалтера
  • Знайдіть партнера
  • Стати партнером
Про нас
  • Наша компанія
  • Торгові активи
  • Зв'яжіться з нами
  • Вакансії
  • Події
  • Подкаст
  • Блог
  • Клієнти
  • Юридичні документи • Конфіденційність
  • Безпека
الْعَرَبيّة 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, електронна комерція, бухгалтерський облік, склад, точка продажу, управління проектами тощо.

Унікальна пропозиція 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