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
    • Validations
    • 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
    • Épicerie
    • Quincaillerie
    • Magasin de jouets
    Food & Hospitality
    • 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
    • Brewery
    • Cadeaux d'entreprise
    Santé & Fitness
    • Club de sports
    • Opticien
    • Salle de fitness
    • Praticiens bien-être
    • Pharmacie
    • Salon de coiffure
    Trades
    • Bricoleur
    • Matériel informatique et 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
    Browse all 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
    • Devenez partenaire
    • Services for Partners
    • 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

Odoo is the world's easiest all-in-one management software.
It includes hundreds of business apps:

  • CRM
  • e-Commerce
  • Comptabilité
  • Inventaire
  • PoS
  • Projet
  • MRP
All apps
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

ERROR: insert or update on table "student_marks" violates foreign key constraint "student_marks_subjname_fkey"

S'inscrire

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

Cette question a été signalée
1 Répondre
12037 Vues
Avatar
Keerthi

ERROR: insert or update on table "student_marks" violates foreign key constraint "student_marks_subjname_fkey"
DETAIL:  Key (subjname)=(38) is not present in table "student_subject".
My Model is:-

# -*- coding: utf-8 -*-

from odoo import models, fields, api, tools, _
from datetime import datetime, date
from odoo.tools import DEFAULT_SERVER_DATE_FORMAT
from odoo.exceptions import ValidationError

#Model of student
class StudentStudent(models.Model):
    _name = 'student.student'
    _order = "admission_no desc"

    name = fields.Char(string = 'Name', required = True)
    student_dob = fields.Date(string = "Date of Birth")
    age = fields.Integer(string = 'Age', compute = 'calcu_age',
        store = True)
    admission_no = fields.Integer('Admission No', required = True)
    place = fields.Char(string = 'Place', required = True)
    photo = fields.Binary(string = 'Image')
    phone_number = fields.Char(string = 'Phone Number', required = True)
    gender = fields.Selection([('male', 'Male'),
                            ('female', 'Female'),
                            ('others', 'Others')],
                            string = 'Gender')
    student_blood_group = fields.Selection([('A+', 'A+ve'),
                                            ('B+', 'B+ve'),
                                            ('O+', 'O+ve'),
                                            ('AB+', 'AB+ve'),
                                             ('A-', 'A-ve'),
                                             ('B-', 'B-ve'),
                                             ('O-', 'O-ve'),
                                             ('AB-', 'AB-ve')],
                                             string = 'Blood Group')
    nationality = fields.Many2one('res.country', string = 'Nationality')
    branchname = fields.Many2one('student.branch', string = 'Branchname')
    active = fields.Boolean(default = True)
    filteration = fields.Selection(selection = 'addfilter')
    sortingfunction = fields.Selection(selection = 'addsort')
    creating = fields.Char(compute = 'action_create')
    browsing = fields.Char(compute = 'action_browse')
    #Existing=fields.Char(compute='action_exists')
   
    #Method to display name and place using name_get method
    @api.multi
    def name_get(self):
        '''Method to display name and place'''
        return [(rec.id, '[' + rec.name + ']' + rec.place) for rec in self]

    # Validation of Phone Number
    @api.constrains('phone_number')
    def _check_phone_number(self):
        if len(self.phone_number) != 10:
            raise ValidationError(_("Invalid Phone Number..."))

    # Create Orm method for creating a record
    @api.multi
    def action_create(self):
        for record in self:
            if record.name == 'lilly':
                record.create({'name': "Joe",
                                'admission_no': 456,
                                'place': "rtr"})

    #Method to calculate age fom Date of Birth
    @api.depends('student_dob')
    def calcu_age(self):
        '''Method to calculate student age'''
        current_dt = datetime.today()
        for rec in self:
            if rec.student_dob:
                start = datetime.strptime(str(rec.student_dob), DEFAULT_SERVER_DATE_FORMAT)
                age_calc = ((current_dt - start).days / 365)
                # Age should be greater than 0
                if age_calc > 0.0:
                    rec.age = age_calc

    #Browse Orm method to browse recordset based on id
    @api.multi
    def action_browse(self):
        for record in self:
            c=self.env['student.student'].browse([2]).name
            print('\n', c)

    @api.multi
    def addfilter(self):
        print("\n\n\n\n")
        a = self.env['student.student'].search([('active', '=', True)])
        k = a.filtered(lambda r:r.age == 21)
        return [(m.name, (m.name).upper()) for m in k]

    @api.multi
    def addsort(self):
        print("\n\n\n\n")
        a = self.env['student.student'].search([('active', '=', True)])
        k = a.sorted(lambda r:r.age)
        return [(m.name, (m.name).upper()) for m in k]
   

    

#Model of Activity
class StudentActivities(models.Model):
    _inherit = 'student.student'
   
    activity_name = fields.Char(string = 'Activity Name',
        required = True)
    activity_score = fields.Integer(string = 'Activity Score',
        required = True)
 #Model of Teacher
class Teacher(models.Model):
    _name = 'student.teacher'
    _rec_name = 'nametr'

    nametr = fields.Char(string = 'Name', required = True)
    age = fields.Integer(string = 'Age')
    photo = fields.Binary(string = 'Image')
    gender = fields.Selection([('male', 'Male'),
                            ('female', 'Female'),
                            ('others', 'Others')],
                            string='Gender')
    nationality = fields.Many2one('res.country', string = 'Nationality')
    state = fields.Selection([
            ('draft', 'Draft'),
            ('in_progress', 'In Progress'),
            ('done', 'Done')],
            default = 'draft')

    @api.one
    def action_confirm(self):
        self.write({'state': 'in_progress'})
   
    @api.one
    def action_finished(self):
        self.write({'state': 'done'})

#Model of Marklist
class StudentMarkList(models.Model):
    _name = 'student.mark'
    _rec_name = 'student_id'

    student_id = fields.Many2one('student.student',
        string = 'StudentName')
    branch = fields.Many2one('student.branch',
        string = 'Branch Name')
    # Setting Related field
    #age = fields.Integer(related='student_id.age',string='Age')
    '''
    total = fields.Integer(string = 'Total Mark', store = True,
        compute = '_compute_total')'''
    subname = fields.One2many('student.marks', 'subjname',
        string = 'Subjectwise Marks')       
    hide_inv_button = fields.Boolean(copy = False, default = True)
    state = fields.Selection([('confirmed', 'Confirm'),
                            ('cancelled', 'Cancel')],
                            string = 'Status', readonly = True,
                            copy = False, index = True,
                            track_visibility = 'onchange')
                                                           
    #Method of Confirm Button
    @api.multi
    def action_confirm(self):
        self.state = 'confirmed'
        self.hide_inv_button = False
                           
#Model of subject
class StudentSubject(models.Model):
    _name = 'student.subject'
   
    name = fields.Char(string = 'Subject Name')   
    branch_id = fields.Many2one("student.branch", string = "Branch",
        index = True,readonly = "1")

#Model of Branch
class StudentBranch(models.Model):
    _name = 'student.branch'
    _rec_name = 'branchname'
   
    branchname = fields.Char(string = 'BranchName')
    branchcode = fields.Integer(string = 'Branch Code')
    subname = fields.One2many('student.subject', 'branch_id',
        string = 'Subject Name')

#Model of Marks
class StudentMarks(models.Model):
    _name = 'student.marks'
    _rec_name = 'subjname'
   
    subjname = fields.Many2one('student.subject', string = 'Subjectname')
    mark = fields.Integer(string = 'Mark')
    branchmark =fields.Many2one('student.branch', string = "Branch",)
                           
    #Dynamic dropdown to display subname based on branch
    @api.onchange('branchmark')
    def _branch_onchange(self):
        res = {}
        res['domain'] = {'subjname':[('branch_id', '=', self.branchmark.id)]}
        return res
   
# onchange handler for subjectwise branch change
@api.onchange('branchname')
def _onchange_branchname(self):
    # set auto-changing field
    self.branch_id = self.branchname
    # Can optionally return a warning and domains
    return {
        'warning': {
            'title': "Something bad happened",
            'message': "It was very bad indeed",
        }
    }

Please Help...

Thanks in Advance

0
Avatar
Ignorer
Avatar
Caret IT Solutions Pvt. Ltd.
Meilleure réponse

Hi,

Change this field from 

 subjname = fields.Many2one('student.subject', string = 'Subjectname')

to 

 subjname = fields.Many2one('student.mark', string = 'Subjectname')

0
Avatar
Ignorer
Faris Fathurrahman

thanks a lot, even in my case i got mistake in main model field name, but your answered inspired me to find the problem!

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
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
  • Devenez 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 ภาษาไทย 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