Ir al contenido
Odoo Menú
  • Iniciar sesión
  • Pruébalo gratis
  • Aplicaciones
    Finanzas
    • Contabilidad
    • Facturación
    • Gastos
    • Hoja de cálculo (BI)
    • Documentos
    • Firma electrónica
    Ventas
    • CRM
    • Ventas
    • PdV para tiendas
    • PdV para restaurantes
    • Suscripciones
    • Alquiler
    Sitios web
    • Creador de sitios web
    • Comercio electrónico
    • Blog
    • Foro
    • Chat en vivo
    • eLearning
    Cadena de suministro
    • Inventario
    • Manufactura
    • PLM
    • Compras
    • Mantenimiento
    • Calidad
    Recursos humanos
    • Empleados
    • Reclutamiento
    • Vacaciones
    • Evaluaciones
    • Referencias
    • Flotilla
    Marketing
    • Redes sociales
    • Marketing por correo
    • Marketing por SMS
    • Eventos
    • Automatización de marketing
    • Encuestas
    Servicios
    • Proyectos
    • Registro de horas
    • Servicio externo
    • Soporte al cliente
    • Planeación
    • Citas
    Productividad
    • Conversaciones
    • Aprobaciones
    • IoT
    • VoIP
    • Artículos
    • WhatsApp
    Aplicaciones externas Studio de Odoo Plataforma de Odoo en la nube
  • Industrias
    Venta minorista
    • Librería
    • Tienda de ropa
    • Mueblería
    • Tienda de abarrotes
    • Ferretería
    • Juguetería
    Alimentos y hospitalidad
    • Bar y pub
    • Restaurante
    • Comida rápida
    • Casa de huéspedes
    • Distribuidora de bebidas
    • Hotel
    Bienes inmuebles
    • Agencia inmobiliaria
    • Estudio de arquitectura
    • Construcción
    • Gestión de bienes inmuebles
    • Jardinería
    • Asociación de propietarios
    Consultoría
    • Firma contable
    • Partner de Odoo
    • Agencia de marketing
    • Bufete de abogados
    • Adquisición de talentos
    • Auditorías y certificaciones
    Manufactura
    • Textil
    • Metal
    • Muebles
    • Comida
    • Cervecería
    • Regalos corporativos
    Salud y ejercicio
    • Club deportivo
    • Óptica
    • Gimnasio
    • Especialistas en bienestar
    • Farmacia
    • Peluquería
    Trades
    • Personal de mantenimiento
    • Hardware y soporte de TI
    • Sistemas de energía solar
    • Zapateros y fabricantes de calzado
    • Servicios de limpieza
    • Servicios de calefacción, ventilación y aire acondicionado
    Otros
    • Organización sin fines de lucro
    • Agencia para la protección del medio ambiente
    • Alquiler de anuncios publicitarios
    • Fotografía
    • Alquiler de bicicletas
    • Distribuidor de software
    Descubre todas las industrias
  • Odoo Community
    Aprende
    • Tutoriales
    • Documentación
    • Certificaciones
    • Capacitación
    • Blog
    • Podcast
    Fortalece la educación
    • Programa educativo
    • Scale Up! El juego empresarial
    • Visita Odoo
    Obtén el software
    • Descargar
    • Compara ediciones
    • Versiones
    Colabora
    • GitHub
    • Foro
    • Eventos
    • Traducciones
    • Conviértete en partner
    • Servicios para partners
    • Registra tu firma contable
    Obtén servicios
    • Encuentra un partner
    • Encuentra un contador
    • Contacta a un consultor
    • Servicios de implementación
    • Referencias de clientes
    • Soporte
    • Actualizaciones
    GitHub YouTube Twitter LinkedIn Instagram Facebook Spotify
    +1 (650) 691-3277
    Solicita una demostración
  • Precios
  • Ayuda

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

  • CRM
  • e-Commerce
  • Contabilidad
  • Inventario
  • PoS
  • Proyectos
  • MRP
All apps
Debe estar registrado para interactuar con la comunidad.
Todas las publicaciones Personas Insignias
Etiquetas (Ver todo)
odoo accounting v14 pos v15
Acerca de este foro
Debe estar registrado para interactuar con la comunidad.
Todas las publicaciones Personas Insignias
Etiquetas (Ver todo)
odoo accounting v14 pos v15
Acerca de este foro
Ayuda

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

Suscribirse

Reciba una notificación cuando haya actividad en esta publicación

Se marcó esta pregunta
1 Responder
12022 Vistas
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.
Mejor respuesta

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!

¿Le interesa esta conversación? ¡Participe en ella!

Cree una cuenta para poder utilizar funciones exclusivas e interactuar con la comunidad.

Registrarse
Comunidad
  • Tutoriales
  • Documentación
  • Foro
Código abierto
  • Descargar
  • GitHub
  • Runbot
  • Traducciones
Servicios
  • Alojamiento en Odoo.sh
  • Soporte
  • Actualizaciones del software
  • Desarrollos personalizados
  • Educación
  • Encuentra un contador
  • Encuentra un partner
  • Conviértete en partner
Sobre nosotros
  • Nuestra empresa
  • Activos de marca
  • Contáctanos
  • Empleos
  • Eventos
  • Podcast
  • Blog
  • Clientes
  • Legal • Privacidad
  • Seguridad
الْعَرَبيّة 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 es un conjunto de aplicaciones de código abierto que cubren todas las necesidades de tu empresa: CRM, comercio electrónico, contabilidad, inventario, punto de venta, gestión de proyectos, etc.

La propuesta única de valor de Odoo es ser muy fácil de usar y estar totalmente integrado.

Sitio web hecho con

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