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

Display another field in many2one instead of name

Подписаться

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

Этот вопрос был отмечен
many2onerelationshipsearch
3 Ответы
36726 Представления
Аватар
vivek

Hi,

I have a many2one field like this

'product_id': fields.many2one('product.product', 'Product', required=True)

It displays me all the product names (name attribute from product_template class) and stores id inside. I would like to display the part_number of the product instead of name and store id inside. Is there a way to do this in openerp7. Thanks for your time.

7
Аватар
Отменить
Hiral Patel (hip)

Use name_get(), It will be helpful.

Sehrish

By default, Odoo allows searching customers only by name and displays only the name in Many2One fields. This module enhances the Many2One search and display functionality by enabling users to search using multiple fields (Phone, Email, Mobile, etc.) and display multiple values directly inside the Partners Many2One selection.
https://apps.odoo.com/apps/modules/17.0/mh_partner_search_and_display_multiple_field

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

I too find the default name to be inappropriate for some things. Especially with products such as replacement parts for vehicles. They don't have names, just a description and a PN so I've had to change what is used for name. Anyway here is how it is done in Python.

def name_get(self, cr, uid, ids, context=None):
    if context is None:
        context = {}
    if isinstance(ids, (int, long)):
        ids = [ids]

    res = []
    for record in self.browse(cr, uid, ids, context=context):
        name = record.company
        res.append((record.id, name))

    return res

This overrides the default name_get method for the model and permits modification of the display name. In this case I am substituting the value of "company" for the actual name. Note this code works with many records or a single record to be compatible with both tree and form views. In your case you are looking at an already complicated name_get method for product.product.

def name_get(self, cr, user, ids, context=None):
    if context is None:
        context = {}
    if isinstance(ids, (int, long)):
        ids = [ids]
    if not len(ids):
        return []
    def _name_get(d):
        name = d.get('name','')
        code = d.get('default_code',False)
        if code:
            name = '[%s] %s' % (code,name)
        if d.get('variants'):
            name = name + ' - %s' % (d['variants'],)
        return (d['id'], name)

    partner_id = context.get('partner_id', False)

    result = []
    for product in self.browse(cr, user, ids, context=context):
        sellers = filter(lambda x: x.name.id == partner_id, product.seller_ids)
        if sellers:
            for s in sellers:
                mydict = {
                          'id': product.id,
                          'name': s.product_name or product.name,
                          'default_code': s.product_code or product.default_code,
                          'variants': product.variants
                          }
                result.append(_name_get(mydict))
        else:
            mydict = {
                      'id': product.id,
                      'name': product.name,
                      'default_code': product.default_code,
                      'variants': product.variants
                      }
            result.append(_name_get(mydict))
    return result

The good part of this is most of the work is done for you. In mydict change product.name to product.field_you_want_instead.

4
Аватар
Отменить
Аватар
vivek
Автор Лучший ответ

Hi,

My basic intention was to display Part-Number of the product for all products and give ability to search by Part-Number.

I accomplished it this way in product.product class,(Code between #Vivek and #End are my code snippets)

def name_get(self, cr, user, ids, context=None):
    if context is None:
        context = {}
    if isinstance(ids, (int, long)):
        ids = [ids]
    if not len(ids):
        return []
    def _name_get(d):
        name = d.get('name','')
        code = d.get('default_code',False)
        # Vivek
        part_number = d.get('part_number',False)
        if part_number:
            name = '%s-%s' % (name,part_number)
        #End
        elif code:
            name = '[%s] %s' % (code,name)
        elif d.get('variants'):
            name = name + ' - %s' % (d['variants'],)
        return (d['id'], name)

    partner_id = context.get('partner_id', False)

    result = []
    for product in self.browse(cr, user, ids, context=context):
        sellers = filter(lambda x: x.name.id == partner_id, product.seller_ids)
        # Vivek
        prd_temp = self.pool.get('product.template').browse(cr, user, product.id, context=context)
        # End
        if sellers:
            for s in sellers:
                mydict = {
                          'id': product.id,
                          'name': s.product_name or product.name,
                          #vivek
                          'part_number': prd_temp.part_number,
                          #End
                          'default_code': s.product_code or product.default_code,
                          'variants': product.variants
                          }
                result.append(_name_get(mydict))
        else:
            mydict = {
                      'id': product.id,
                      'name': product.name,
                      #vivek
                      'part_number': prd_temp.part_number,
                      #End
                      'default_code': product.default_code,
                      'variants': product.variants
                      }
            result.append(_name_get(mydict))
    return result

def name_search(self, cr, user, name='', args=None, operator='ilike', context=None, limit=100):
    if not args:
        args = []
    if name:
        ids = self.search(cr, user, [('default_code','=',name)]+ args, limit=limit, context=context)
        if not ids:
            ids = self.search(cr, user, [('ean13','=',name)]+ args, limit=limit, context=context)
        if not ids:
            # Do not merge the 2 next lines into one single search, SQL search performance would be abysmal
            # on a database with thousands of matching products, due to the huge merge+unique needed for the
            # OR operator (and given the fact that the 'name' lookup results come from the ir.translation table
            # Performing a quick memory merge of ids in Python will give much better performance
            ids = set()
            ids.update(self.search(cr, user, args + [('default_code',operator,name)], limit=limit, context=context))
            if not limit or len(ids) < limit:
                # we may underrun the limit because of dupes in the results, that's fine
                ids.update(self.search(cr, user, args + [('name',operator,name)], limit=(limit and (limit-len(ids)) or False) , context=context))
                # vivek
                # Purpose  : To filter the product by using part_number
                ids.update(self.search(cr, user, args + [('part_number',operator,name)], limit=(limit and (limit-len(ids)) or False) , context=context))
                #End
            ids = list(ids)
        if not ids:
            ptrn = re.compile('(\[(.*?)\])')
            res = ptrn.search(name)
            if res:
                ids = self.search(cr, user, [('default_code','=', res.group(2))] + args, limit=limit, context=context)
    else:
        ids = self.search(cr, user, args, limit=limit, context=context)
    result = self.name_get(cr, user, ids, context=context)
    return result

But the problem with this particular functionality is "It's a global change" wherever you get to list the products the display will be Product Name - Part Number. If someone can do that better for context specific actions it will be great.

Thanks mike for your valuable input (It was useful and i've upvoted it)

Further answers are eagerly welcome. :)

3
Аватар
Отменить
mike

Thank you! Good job with the name search override. Do you need to change the displayed name dynamically with various views? I guess you could try setting context values within a view and adding Python to trap for them.

Alexandre Boily

I worked around the "global change" problem by having a middleman model between the main view and the target object. I have a many2one field in a custom model that points to PO lines. I needed to show both the product name and some analytic account information in the form, so I created a new class with the name_get() override.

Аватар
Niyas Raphy (Walnut Software Solutions)
Лучший ответ

Hi,

By using name_get function or by adding rec_name for the model we can show the other fields in the drop down instead of name, which is the default option.

Odoo Name get function: https://www.youtube.com/watch?v=aT_tsfW5HaQ

Thanks

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

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

Регистрация
Похожие посты Ответы Просмотры Активность
how to set default value in many2one field
module many2one relationship search
Аватар
Аватар
Аватар
2
окт. 24
10029
Analytic account search
many2one search
Аватар
0
мар. 15
4245
Adding BOM lines: product search scope
product many2one relationship search bom
Аватар
0
окт. 23
1682
many2one field search for by multiple criteria (name, phone number, etc)?
many2one search odoo
Аватар
Аватар
Аватар
2
февр. 25
9411
How to open direct list view instead of select "Search More.." in Many2one field for Odoo16
many2one search V16
Аватар
Аватар
1
сент. 24
3159
Сообщество
  • Видео уроки
  • Документация
  • Форум
Открытый исходный код
  • Скачать
  • 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