Перейти к содержимому
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
Об этом форуме
Помощь

How to keep multiple Many2many fields on the same model

Подписаться

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

Этот вопрос был отмечен
modelsmany2manymultiple_values
4 Ответы
21726 Представления
Аватар
arthur

Hello, I am trying to create a model that have multiple Many2many fields that relates to the "product.product" model. Basically, the model will have four list, each one containing different products.

My model is the following:

class SubscriptionBasket(models.Model):
    _name="subscription.basket"
    name = fields.Char("Nome", required=True)
    legumes = fields.Many2many(
        'product.product',
        string='Legumes',
    )
    frutas = fields.Many2many(
        'product.product',
        string='Frutas',
    )
    verduras = fields.Many2many(
        'product.product',
        string='Verduras',
    )
    temperos = fields.Many2many(
        'product.product',
        string='Temperos',
    )


The problem however is that when I choose a product to one of the fields and then save, all fields get this product as well.

As an example, I overwrote the create function to get logs:

@api.model
def create(self, vals):
    _logger.info("Vals received on creation: %s", vals)
    res = super(SubscriptionBasket, self).create(vals)
    _logger.info("Field temperos on creation response: %s", res.temperos)
    return res


Then, when creating a record, informing a product just to the fields "legumes", I get the following log for the vals I received:

    Vals received on creation: {'name': 'Cesta', 'temperos': [[6, False, []]], 'frutas': [[6, False, []]], 'date_start': '2019-02-05',     'verduras': [[6, False, []]], 'legumes': [[6, False, [6952]]], 'date_end': '2019-02-08'}

And the following log for the field "temperos", which I would expect to be empty, on the creation response:

    Field temperos on creation response: product.product(6952,)

What am I missing here?

2
Аватар
Отменить
Sehrish

Create many2many field: https://learnopenerp.blogspot.com/2018/12/add-domain-on-many2many-field-in-odoo.html

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

Hello Arthur,

Try to define like below:

class SubscriptionBasket(models.Model):
    _name="subscription.basket"

    name = fields.Char("Nome", required=True)
    legumes = fields.Many2many('product.product', 'product_legumes', 'product_id', 'legumes_id', string='Legumes')
    frutas = fields.Many2many('product.product', 'product_frutas', 'product_id', 'frutas_id', string='Frutas')
    verduras = fields.Many2many('product.product', 'product_verduras', 'product_id', 'verduras_id', string='Verduras')
    temperos = fields.Many2many('product.product', 'product_temperos', 'product_id', 'temperos_id',string='Temperos')


Hope it will works for you.

Thanks,

10
Аватар
Отменить
arthur
Автор

Thank you! 'product_legumes', 'product_id', 'legumes_id' are the name for relation, column1 and column2, respectively, right? How do I know these names?

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

You can look in the Base Model as well.

the description


class Many2many(_RelationalMulti):
""" Many2many field; the value of such a field is the recordset.


:param comodel_name: name of the target model (string)

The attribute ``comodel_name`` is mandatory except in the case of related
fields or field extensions.


The attribute ``comodel_name`` is mandatory except in the case of related
fields or field extensions.
:param relation: optional name of the table that stores the relation in
the database (string)


the database (string)
:param column1: optional name of the column referring to "these" records
in the table ``relation`` (string)


in the table ``relation`` (string)
:param column2: optional name of the column referring to "those" records
in the table ``relation`` (string)

The attributes ``relation``, ``column1`` and ``column2`` are optional. If not
given, names are automatically generated from model names, provided
``model_name`` and ``comodel_name`` are different!


in the table ``relation`` (string)
The attributes ``relation``, ``column1`` and ``column2`` are optional. If not
given, names are automatically generated from model names, provided
``model_name`` and ``comodel_name`` are different!
:param domain: an optional domain to set on candidate values on the
client side (domain or string)


client side (domain or string)
:param context: an optional context to use on the client side when
handling that field (dictionary)


handling that field (dictionary)
:param limit: optional limit to use upon read (integer)


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

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

Регистрация
Похожие посты Ответы Просмотры Активность
How can we access child model filed in parents model
models many2many v15 childclass
Аватар
1
июл. 22
2742
I can't save the field relation to my new model Решено
modules models many2many odoo8
Аватар
Аватар
Аватар
3
февр. 17
4492
How to get the tax_id from a sale order? (Customize Quotation template) Решено
models quotation many2many model
Аватар
Аватар
1
мар. 15
6870
How can I use two models in an API (foreign key - relations)?
models
Аватар
0
дек. 24
2148
Import Data From Another Model Решено
models
Аватар
Аватар
1
мар. 24
3264
Сообщество
  • Видео уроки
  • Документация
  • Форум
Открытый исходный код
  • Скачать
  • 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