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
    • Real Estate Agency
    • Архітектурна фірма
    • Будівництво
    • Управління нерухомістю
    • Садівництво
    • Асоціація власників нерухомості
    Consulting
    • Accounting Firm
    • Партнер Odoo
    • Marketing Agency
    • Юридична фірма
    • Придбання Талантів
    • Аудит та сертифікація
    Виробництво
    • Textile
    • Metal
    • Furnitures
    • Food
    • Brewery
    • Корпоративні подарунки
    Здоров'я & Фітнес
    • Спортивний клуб
    • Оптика
    • Фітнес-центр
    • Практики здоров'я
    • Аптека
    • Салон краси
    Trades
    • Ремонтник
    • IT-обладнання та Підтримка
    • Solar Energy Systems
    • Shoe Maker
    • Cleaning Services
    • HVAC Services
    Others
    • 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
Про цей форум
Допомога

how to count on selection value

Підписатися

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

Це запитання позначене
selectioncountodoo
2 Відповіді
1975 Переглядів
Аватар
mmd

I making a module for student's to select their lunch in a day and it's a selection .
how i can see how many student's select food1 and how many select food2 ?


this is my food class :

class Lunch(models.Model):
_name = "food.foods"

name = fields.Char(string="نام غذا", required=True)
food_type = fields.Selection([('withrice','WithRice'),('whitoutrice' , 'WithoutRice')] , string="select" )

and this is my days class :

class DayOfWeek(models.Model):
_name = 'food.days'
_description = 'days of week'

name = fields.Char(string='day' , compute='_complite_name')
date = fields.Date(string='date', required=True)
week_id = fields.Many2one('food.weeks', string='week')
food_id = fields.Many2many('food.foods', string='food name')






0
Аватар
Відмінити
Аватар
Jainesh Shah(Aktiv Software)
Найкраща відповідь

Hello mmd,


To see how many students selected Food 1 and Food 2, you can add two counters in your "food.days" model.

Based on your Many2many relationship with food_ids, you can count the selections as follows:


Add compute fields:

//Code in Comment//

Hope this Helps,

If you need any help in customization feel free to contact us.


Thanks & Regards,

Email:  odoo@aktivsoftware.com           

Skype: kalpeshmaheshwari

0
Аватар
Відмінити
Jainesh Shah(Aktiv Software)

Code :
with_rice_count = fields.Integer(string='With Rice Count',
compute='_compute_food_counts',
store=True)

without_rice_count = fields.Integer(string='Without Rice Count',
compute='_compute_food_counts',
store=True)

Compute method:
@api.depends('food_id')
def _compute_food_counts(self):
for record in self:
with_rice = record.food_id.filtered(
lambda f: f.food_type == 'withrice')
without_rice = record.food_id.filtered(
lambda f: f.food_type == 'whitoutrice')
record.with_rice_count = len(with_rice)
record.without_rice_count = len(without_rice)

Аватар
CodeWasher
Найкраща відповідь

To achieve the functionality where you can see how many students have selected food1 and how many have selected food2, you need to create a relation between the DayOfWeek and the students' selection of a specific lunch. You can create an additional model to capture each student's food selection on a particular day.


Here's an overview of what you need to add:


Create a new model to track student food selection.

Link the new model to the DayOfWeek and Lunch models, as well as to the student.



Updated Models:

Add Student Food Selection Model: This new model will track each student's food choice for a given day.



from odoo import models, fields


class Student(models.Model):

    _name = 'food.student'

    _description = 'Student'


    name = fields.Char(string='Student Name', required=True)

    student_id = fields.Char(string='Student ID', required=True)


class Lunch(models.Model):

    _name = "food.foods"


    name = fields.Char(string="Food Name", required=True)

    food_type = fields.Selection([('withrice', 'WithRice'), ('whitoutrice', 'WithoutRice')], string="Select")


class DayOfWeek(models.Model):

    _name = 'food.days'

    _description = 'Days of the Week'


    name = fields.Char(string='Day', compute='_compute_name')

    date = fields.Date(string='Date', required=True)

    week_id = fields.Many2one('food.weeks', string='Week')

    food_ids = fields.Many2many('food.foods', string='Food Name')


class StudentFoodSelection(models.Model):

    _name = 'food.student.selection'

    _description = 'Student Food Selection'


    student_id = fields.Many2one('food.student', string='Student', required=True)

    day_id = fields.Many2one('food.days', string='Day', required=True)

    food_id = fields.Many2one('food.foods', string='Selected Food', required=True)






Explanation:

Student model:


Added a Student model to represent each student. You might already have a similar student model, in which case, you can skip this one.

Lunch model (food.foods):


This is your existing Lunch model. No changes here.

DayOfWeek model (food.days):


This is also your existing model for representing each day. The only change is a change in the field name from food_id to food_ids to make it clear it's a list of options.

StudentFoodSelection model (food.student.selection):


This new model captures each student's food choice on a given day. It has three fields:

student_id: A reference to the student.

day_id: A reference to the day for which the selection is made.

food_id: A reference to the food selected by the student




Computing the Selection Count

To calculate how many students have selected food1 or food2, you can add a computed field on the DayOfWeek model or create a method to run the calculation:



class DayOfWeek(models.Model):

    _inherit = 'food.days'


    food_selection_summary = fields.Text(string='Food Selection Summary', compute='_compute_food_selection_summary')


    def _compute_food_selection_summary(self):

        for record in self:

            summary = ""

            food_counts = {}

            selections = self.env['food.student.selection'].search([('day_id', '=', record.id)])

            for selection in selections:

                if selection.food_id.name not in food_counts:

                    food_counts[selection.food_id.name] = 0

                food_counts[selection.food_id.name] += 1


            summary = "\n".join(f"{food_name}: {count} students" for food_name, count in food_counts.items())

            record.food_selection_summary = summary





0
Аватар
Відмінити
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 Відповіді Переглядів Дія
I want to count total no. of bills done by a biller...But always shows 1 from the "highest_biller"...
count odoo
Аватар
0
лип. 21
3121
Add value to selection field without coding
selection odoo
Аватар
Аватар
Аватар
3
груд. 19
4980
How do I get the value of a selection field - widget=radio ?
selection odoo odoo12
Аватар
0
квіт. 22
5185
How to add new value in Selection in Settings Вирішено
settings selection odoo
Аватар
Аватар
1
трав. 21
4560
Odoo Selection field issue Вирішено
selection odoo odoo12 odoo12.0
Аватар
Аватар
Аватар
Аватар
3
бер. 24
7971
Спільнота
  • Навчальний посібник
  • Документація
  • Форум
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