Skip to Content
Odoo Menú
  • Registra entrada
  • Prova-ho gratis
  • Aplicacions
    Finances
    • Comptabilitat
    • Facturació
    • Despeses
    • Full de càlcul (IA)
    • Documents
    • Signatura
    Vendes
    • CRM
    • Vendes
    • Punt de venda per a botigues
    • Punt de venda per a restaurants
    • Subscripcions
    • Lloguer
    Imatges de llocs web
    • Creació de llocs web
    • Comerç electrònic
    • Blog
    • Fòrum
    • Xat en directe
    • Aprenentatge en línia
    Cadena de subministrament
    • Inventari
    • Fabricació
    • PLM
    • Compres
    • Manteniment
    • Qualitat
    Recursos humans
    • Empleats
    • Reclutament
    • Absències
    • Avaluacions
    • Recomanacions
    • Flota
    Màrqueting
    • Màrqueting Social
    • Màrqueting per correu electrònic
    • Màrqueting per SMS
    • Esdeveniments
    • Automatització del màrqueting
    • Enquestes
    Serveis
    • Projectes
    • Fulls d'hores
    • Servei de camp
    • Suport
    • Planificació
    • Cites
    Productivitat
    • Converses
    • Validacions
    • IoT
    • VoIP
    • Coneixements
    • WhatsApp
    Aplicacions de tercers Odoo Studio Plataforma d'Odoo al núvol
  • Sectors
    Comerç al detall
    • Llibreria
    • Botiga de roba
    • Botiga de mobles
    • Botiga d'ultramarins
    • Ferreteria
    • Botiga de joguines
    Food & Hospitality
    • Bar i pub
    • Restaurant
    • Menjar ràpid
    • Guest House
    • Distribuïdor de begudes
    • Hotel
    Immobiliari
    • Agència immobiliària
    • Estudi d'arquitectura
    • Construcció
    • Gestió immobiliària
    • Jardineria
    • Associació de propietaris de béns immobles
    Consultoria
    • Empresa comptable
    • Partner d'Odoo
    • Agència de màrqueting
    • Bufet d'advocats
    • Captació de talent
    • Auditoria i certificació
    Fabricació
    • Textile
    • Metal
    • Mobles
    • Menjar
    • Brewery
    • Regals corporatius
    Salut i fitness
    • Club d'esport
    • Òptica
    • Centre de fitness
    • Especialistes en benestar
    • Farmàcia
    • Perruqueria
    Trades
    • Servei de manteniment
    • Hardware i suport informàtic
    • Sistemes d'energia solar
    • Shoe Maker
    • Serveis de neteja
    • Instal·lacions HVAC
    Altres
    • Nonprofit Organization
    • Agència del medi ambient
    • Lloguer de panells publicitaris
    • Fotografia
    • Lloguer de bicicletes
    • Distribuïdors de programari
    Browse all Industries
  • Comunitat
    Aprèn
    • Tutorials
    • Documentació
    • Certificacions
    • Formació
    • Blog
    • Pòdcast
    Potenciar l'educació
    • Programa educatiu
    • Scale-Up! El joc empresarial
    • Visita Odoo
    Obtindre el programari
    • Descarregar
    • Comparar edicions
    • Novetats de les versions
    Col·laborar
    • GitHub
    • Fòrum
    • Esdeveniments
    • Traduccions
    • Converteix-te en partner
    • Services for Partners
    • Registra la teva empresa comptable
    Obtindre els serveis
    • Troba un partner
    • Troba un comptable
    • Contacta amb un expert
    • Serveis d'implementació
    • Referències del client
    • Suport
    • Actualitzacions
    Github Youtube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Programar una demo
  • Preus
  • Ajuda

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

  • CRM
  • e-Commerce
  • Comptabilitat
  • Inventari
  • PoS
  • Projectes
  • MRP
All apps
You need to be registered to interact with the community.
All Posts People Badges
Etiquetes (View all)
odoo accounting v14 pos v15
About this forum
You need to be registered to interact with the community.
All Posts People Badges
Etiquetes (View all)
odoo accounting v14 pos v15
About this forum
Ajuda

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

Subscriure's

Get notified when there's activity on this post

This question has been flagged
1 Respondre
12027 Vistes
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
Descartar
Avatar
Caret IT Solutions Pvt. Ltd.
Best Answer

Hi,

Change this field from 

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

to 

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

0
Avatar
Descartar
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!

Enjoying the discussion? Don't just read, join in!

Create an account today to enjoy exclusive features and engage with our awesome community!

Registrar-se
Community
  • Tutorials
  • Documentació
  • Fòrum
Codi obert
  • Descarregar
  • GitHub
  • Runbot
  • Traduccions
Serveis
  • Allotjament a Odoo.sh
  • Suport
  • Actualització
  • Desenvolupaments personalitzats
  • Educació
  • Troba un comptable
  • Troba un partner
  • Converteix-te en partner
Sobre nosaltres
  • La nostra empresa
  • Actius de marca
  • Contacta amb nosaltres
  • Llocs de treball
  • Esdeveniments
  • Pòdcast
  • Blog
  • Clients
  • Informació legal • Privacitat
  • Seguretat
الْعَرَبيّة 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 és un conjunt d'aplicacions empresarials de codi obert que cobreix totes les necessitats de la teva empresa: CRM, comerç electrònic, comptabilitat, inventari, punt de venda, gestió de projectes, etc.

La proposta única de valor d'Odoo és ser molt fàcil d'utilitzar i estar totalment integrat, ambdues alhora.

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