Se rendre au contenu
Odoo Menu
  • Se connecter
  • Essai gratuit
  • Applications
    Finance
    • Comptabilité
    • Facturation
    • Notes de frais
    • Feuilles de calcul (BI)
    • Documents
    • Signature
    Ventes
    • CRM
    • Ventes
    • PdV Boutique
    • PdV Restaurant
    • Abonnements
    • Location
    Sites web
    • Site Web
    • eCommerce
    • Blog
    • Forum
    • Live Chat
    • eLearning
    Chaîne d'approvisionnement
    • Inventaire
    • Fabrication
    • PLM
    • Achats
    • Maintenance
    • Qualité
    Ressources Humaines
    • Employés
    • Recrutement
    • Congés
    • Évaluations
    • Recommandations
    • Parc automobile
    Marketing
    • Marketing Social
    • E-mail Marketing
    • SMS Marketing
    • Événements
    • Marketing Automation
    • Sondages
    Services
    • Projet
    • Feuilles de temps
    • Services sur Site
    • Assistance
    • Planification
    • Rendez-vous
    Productivité
    • Discussion
    • Intelligence artificielle
    • Internet des Objets
    • VoIP
    • Connaissances
    • WhatsApp
    Applications tierces Odoo Studio Plateforme Cloud d'Odoo
  • Industries
    Commerce de détail
    • Librairie
    • Magasin de vêtements
    • Magasin de meubles
    • Supermarché
    • Quincaillerie
    • Magasin de jouets
    Restauration & Hôtellerie
    • Bar et Pub
    • Restaurant
    • Fast-food
    • Maison d’hôtes
    • Distributeur de boissons
    • Hôtel
    Immobilier
    • Agence immobilière
    • Cabinet d'architecture
    • Construction
    • Gestion immobilière
    • Jardinage
    • Association de copropriétaires
    Consultance
    • Cabinet d'expertise comptable
    • Partenaire Odoo
    • Agence Marketing
    • Cabinet d'avocats
    • Aquisition de talents
    • Audit & Certification
    Fabrication
    • Textile
    • Métal
    • Meubles
    • Alimentation
    • Brasserie
    • Cadeaux d'entreprise
    Santé & Fitness
    • Club de sports
    • Opticien
    • Salle de fitness
    • Praticiens bien-être
    • Pharmacie
    • Salon de coiffure
    Commerce
    • Homme à tout faire
    • Matériel informatique & support
    • Systèmes photovoltaïques
    • Cordonnier
    • Services de nettoyage
    • Services CVC
    Autres
    • Organisation à but non lucratif
    • Agence environnementale
    • Location de panneaux d'affichage
    • Photographie
    • Leasing de vélos
    • Revendeur de logiciel
    Parcourir toutes les industries
  • Communauté
    Apprenez
    • Tutoriels
    • Documentation
    • Certifications
    • Formation
    • Blog
    • Podcast
    Renforcer l'éducation
    • Programme éducatif
    • Business Game Scale-Up!
    • Rendez-nous visite
    Obtenir le logiciel
    • Téléchargement
    • Comparez les éditions
    • Versions
    Collaborer
    • Github
    • Forum
    • Événements
    • Traductions
    • Devenir partenaire
    • Services pour partenaires
    • Enregistrer votre cabinet comptable
    Nos Services
    • Trouver un partenaire
    • Trouver un comptable
    • Rencontrer un conseiller
    • Services de mise en œuvre
    • Références clients
    • Assistance
    • Mises à niveau
    Github Youtube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Obtenir une démonstration
  • Tarification
  • Aide
Vous devez être inscrit pour interagir avec la communauté.
Toutes les publications Personnes Badges
Étiquettes (Voir toutl)
odoo accounting v14 pos v15
À propos de ce forum
Vous devez être inscrit pour interagir avec la communauté.
Toutes les publications Personnes Badges
Étiquettes (Voir toutl)
odoo accounting v14 pos v15
À propos de ce forum
Aide

Creating a One2many record with code

S'inscrire

Recevez une notification lorsqu'il y a de l'activité sur ce poste

Cette question a été signalée
codeone2manymodelsautomaticmodel
1 Répondre
10743 Vues
Avatar
Wojciech Dobrychłop

Hello, I am currently working on a module that has a model with a start and end date. I'm trying to work out how to create one2many records for each day from start to end, automatically during the creation of a record. See the code:

class Order(models.Model):
_name = 'tms.order'
company_id = fields.Many2one('res.company',string = 'Client')
description = fields.Text()
start_date = fields.Datetime('Start Date',required = True)
end_date = fields.Datetime('End Date',required = True)
start_location = fields.Char()
end_location = fields.Char()
driver = fields.Many2one('hr.employee',string = 'Driver',required = True)
vehicle = fields.Many2one('fleet.vehicle')
working_days = fields.One2many('tms.day','order', ondelete='cascade')

@api.model
def create(self, vals):
print(vals)
start = parser.parse(vals['start_date'])
stop = parser.parse(vals['end_date'])
if start < stop:
while start < (stop + timedelta(days=1)):
vals['working_days'] = self.env['tms.day'].create((0,0,{'date':start, 'driver': vals['driver']}))
start = start + timedelta(days=1) # increase day one by one
return super(Order, self).create(vals)

class Day(models.Model):
_name= 'tms.day'

date = fields.Date()
utilisation_ratio = fields.Float("Utilisation ratio", compute='calculate_utilisation_ratio')
driver = fields.Many2one('hr.employee',string = 'Driver')
order = fields.Many2one('tms.order')


@api.depends('date')
def calculate_utilisation_ratio(self):
total_number_of_drivers = self.count_total_drivers()
for day in self:
drivers_working_today = self.env['tms.day'].search_count([('date','=',day.date)])
day.utilisation_ratio = drivers_working_today/total_number_of_drivers

def count_total_drivers(self):
return self.env['hr.employee'].search_count([])


The above code produces tms.day records automatically with the creation of an tms.order, but the tms.days are not linked to any tms.orders. How can I link the Orders to the Days?

0
Avatar
Ignorer
Avatar
Sudhir Arya (ERP Harbor Consulting Services)
Meilleure réponse

Try the following code in your create method by replacing this code:

vals['working_days'] = self.env['tms.day'].create((0,0,{'date':start, 'driver': vals['driver']}))

vals.update({'working_days': [(0, 0, {'date':start, 'driver': vals.get('driver')})]}) # link working days with the tms order


2
Avatar
Ignorer
Wojciech Dobrychłop
Auteur

This creates a successfully linked Day record, but only one, for the last day of the Order. How can I change it to create records for each day the Order takes place (if the Order has a start date of 10th and end date of 12th, create a Day for the 10th, 11th, and 12th)?

Vous appréciez la discussion ? Ne vous contentez pas de lire, rejoignez-nous !

Créez un compte dès aujourd'hui pour profiter de fonctionnalités exclusives et échanger avec notre formidable communauté !

S'inscrire
Publications associées Réponses Vues Activité
Store many2one model records in model with one2many field - how?
many2one one2many models model
Avatar
Avatar
Avatar
Avatar
3
mars 15
7472
How can i link a model to its ownself?
one2many model
Avatar
Avatar
1
mars 15
5820
a model based on a hand written sql query Résolu
models sql model
Avatar
Avatar
1
juil. 23
4034
Odoo 'build a module'...Model not seen in my module
models model tutorial
Avatar
Avatar
4
nov. 20
9361
Why can't i find some models in db? Résolu
models model odoov12
Avatar
Avatar
1
mars 19
5191
Communauté
  • Tutoriels
  • Documentation
  • Forum
Open Source
  • Téléchargement
  • Github
  • Runbot
  • Traductions
Services
  • Hébergement Odoo.sh
  • Assistance
  • Migration
  • Développements personnalisés
  • Éducation
  • Trouver un comptable
  • Trouver un partenaire
  • Devenir partenaire
À propos
  • Notre société
  • Actifs de la marque
  • Contactez-nous
  • Emplois
  • Événements
  • Podcast
  • Blog
  • Clients
  • Informations légales • Confidentialité
  • Sécurité.
الْعَرَبيّة 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 Svenska ภาษาไทย Türkçe українська Tiếng Việt

Odoo est une suite d'applications open source couvrant tous les besoins de votre entreprise : CRM, eCommerce, Comptabilité, Inventaire, Point de Vente, Gestion de Projet, etc.

Le positionnement unique d'Odoo est d'être à la fois très facile à utiliser et totalement intégré.

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