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

Custom code: Key columns are of incompatible types: character varying and integer

Suscribirse

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

Se marcó esta pregunta
typeforeignkeymismatch
2 Respuestas
2535 Vistas
Avatar
Nicolás

Hi everyone!

I have this error:


psycopg2.errors.DatatypeMismatch: foreign key constraint "project_project_laboratorio_fkey" cannot be implemented
DETAIL:  Key columns "laboratorio" and "id" are of incompatible types: character varying and integer.


I have created a model "areas" (Table in database) to use it in a many2one field in a "project.project" inherited custom module I made. I loaded registers in my "areas" module in the python file.


  @api.model

  def init(self):

        default_data = [

            {'area_ejecutante': 'lie', 'laboratorio': 'lide'},

            {'area_ejecutante': 'ima', 'laboratorio': 'pintura'},

            {'area_ejecutante': 'lie', 'laboratorio': 'laie'},

            {'area_ejecutante': 'ima', 'laboratorio': 'mecanica'},

        ]

        for data in default_data:

        # Ensure no duplicates

            if not self.search([('area_ejecutante', '=', data['area_ejecutante']),

                                ('laboratorio', '=', data['laboratorio'])]):

                self.create(data)



Now I commented all the code and unlinked the "areas" model in the __init__.py . 

And I have this error.


Any idea how can I fix it?

Thanks in advance, Nicolás

0
Avatar
Descartar
Dương Nguyễn

Many2one use _rec_name property and you need to have _compute_display_name method
P/s: can you mark my answer as best one please, thank in advance

Avatar
Dương Nguyễn
Mejor respuesta

No one create model record in the init method, i think you should use data.xml file or use post_init_hook please

0
Avatar
Descartar
Avatar
Nicolás
Autor Mejor respuesta

Hi Dương!

Thanks for your answer.


I think what you mentioned could be the problem. Do you have any doc or vid on how to create model records using data.xml?


I have reset the code to my last working commit but I still have this issue because the foreign key remains created. I'll proceed by deleting the foreign key directly through the database,

0
Avatar
Descartar
Dương Nguyễn

How do you define your model and have you try new database ?

Nicolás
Autor

Hi Dương,
I defined my module like this:

from odoo import api, models, fields

class AreasEjecutantesModel(models.Model):
_name = 'areas.ejecutantes.model'
_description = 'Modelo para gestionar las áreas ejecutantes y sus laboratorios'

# area_ejecutante1 = fields.Char(string='Area ejecutante1')
area_ejecutante1 = fields.Selection([
('lab1', 'lab_name'),
('lab2', 'lab_name'),
('lab3', 'lab_name'),
('lab4', 'lab_name')
], string="Area Ejecutante", default='lab1')
# laboratorio1 = fields.Char(string='Laboratorio1')
laboratorio1 = fields.Selection([
('sublab1','sublabname'),
('sublab2','sublabname'),
('sublab3','sublabname'),
('sublab4', 'sublabname'),
], string="Laboratorios", default='sublab1')

@api.model
def init(self):
default_data = [
{'area_ejecutante1': 'lab1', 'laboratorio1': 'sublab3'},
{'area_ejecutante1': 'lab2', 'laboratorio1': 'sublab1'},
{'area_ejecutante1': 'lab1', 'laboratorio1': 'sublab4'},
{'area_ejecutante1': 'lab2', 'laboratorio1': 'sublab2'},
]
for data in default_data:
# Ensure no duplicates
if not self.search([('area_ejecutante1', '=', data['area_ejecutante1']),
('laboratorio1', '=', data['laboratorio1'])]):
self.create(data)

By running this code the new table in the pgdb is created and the records are loaded in it.
I visualize the pgdb in pgAdmin

Dương Nguyễn

So your project.project model have m2o of your custom model right, in the __init__.py file you should your custom model first

Nicolás
Autor

Exactly Dương, the project.project model have m2o of my custom model.

I did what you mentioned on the init.py and it solved the problem!! I now can visualize the model in the m2o field!

I have a question. If I want to make it dependent on the value selected in a Selection field, should I use the @api.onchange decorator and change the domain? Or is there another way to achieve this?

This is what I did, but it doesn't work.

@api.onchange('area_ejecutante')
def _onchange_area_ejecutante(self):
if self.area_ejecutante == 'lie':
return {'domain': {'laboratorio1': [('area_ejecutante1', '=', 'lie')]}}
elif self.area_ejecutante == 'ima':
return {'domain': {'laboratorio1': [('area_ejecutante1', '=', 'ima')]}}
else:
return {'domain': {'laboratorio1': []}}

Thank you!

Dương Nguyễn

You can use a compute field instead

Nicolás
Autor

Hi Dương,
do you mean on the many2one field?
By trying to do so (adding the compute="myonchangefunction" on the m2o field) my module fails.

I would need that the options of the m2o field vary depending on the value of a Selection field.

e.g, in the selection field i would choose the laboratory, and m2o field should show the sublabs of the lab selected. Not all the sublabs of all the labs.

Thank you!

Dương Nguyễn

which odoo version?
You onchange function should assign field like this
if self.area_ejecutante1 == '':
self.field = ""

Nicolás
Autor

Hi Dương,
I solved it by following Long's answer in this issue that you were also involved in: https://www.odoo.com/es_ES/forum/ayuda-1/issue-return-dynamic-domain-for-field-with-on-change-method-in-odoo-17-253508.

Thank you so much.

The only thing I need to finish now is how the information is displayed in my Many2one field. Currently, I see the format [modelname, id]. I read that the name_get method should be used, but I haven't been able to make it work yet.

Thank you again. Best regards,

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

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

Registrarse
Publicaciones relacionadas Respuestas Vistas Actividad
space characters are femoved directly after typen them
type
Avatar
0
jul 24
1916
using a attribute of another module table as a foreign key
foreignkey
Avatar
0
feb 18
3965
How to implement foreign key in open erp
foreignkey
Avatar
Avatar
Avatar
2
mar 15
9346
About Odoo Inventory Resuelto
type Inventory
Avatar
Avatar
Avatar
2
dic 24
3534
What is the purpose of Subtypes in Odoo? Resuelto
sub type
Avatar
Avatar
1
jun 23
3571
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.

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