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

How to fix a error with a field unique?

Suscribirse

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

Se marcó esta pregunta
sequenceuniqueres_partner
1 Responder
13939 Vistas
Avatar
Anabela Damas

Hi,

To create a list of clients and suppliers with a sequence number I made like this:

mymodule.py

...
class res_partner(osv.osv):
    _inherit = 'res.partner'
    _name = 'res.partner'

    _columns = {
        'n_client' : fields.char('Client Number', size=64, readonly=True),
        'n_supplier' : fields.char('Supplier Number', size=64, readonly=True),
    }
    _defaults = {
        'n_client': lambda obj, cr, uid, context: '/',
        'n_supplier': lambda obj, cr, uid, context: '/',        
    }
    _sql_constraints = [
        ('name_uniq_1', 'unique(n_client)', 'Number of client must be unique!'),
        ('n_supplier_uniq', 'unique(n_supplier)', 'Number of supplier must be unique!'),        
    ]

    def create(self, cr, uid, vals, context=None):
        if vals.get('n_client','/')=='/':
            vals['n_client'] = self.pool.get('ir.sequence').get(cr, uid, 'res.partner.customer') or '/'     
        if vals.get('n_supplier','/')=='/':
            vals['n_supplier'] = self.pool.get('ir.sequence').get(cr, uid, 'res.partner.supplier') or '/'
        return super(res_partner,self).create(cr, uid, vals, context=context)

    def copy(self, cr, uid, id, default=None, context=None):
        default.update({
            'n_client': self.pool.get('ir.sequence').get(cr, uid, 'res.partner.customer'),
            'n_supplier': self.pool.get('ir.sequence').get(cr, uid, 'res.partner.supplier')
        })
        return super(res_partner, self).copy(cr, uid, id, default, context)
res_partner()
...

mymoodule_sequence.xml

<?xml version="1.0" encoding="utf-8"?>
<openerp>
    <data noupdate="1">
            <record model="ir.sequence.type" id="seq_type_res_partner">
                <field name="name">number_client_sequence</field>
                <field name="code">res.partner.customer</field>
            </record>
            <record model="ir.sequence" id="seq_res_partner">
                <field name="name">number_client_sequence</field>
                <field name="code">res.partner.customer</field>
                <field name="prefix">C</field>
                <field name="padding">5</field>
            </record>
            <record model="ir.sequence.type" id="seq_type_res_supplier">
                <field name="name">number_supplier_sequence</field>
                <field name="code">res.partner.supplier</field>
            </record>
            <record model="ir.sequence" id="seq_res_supplier">
                <field name="name">number_supplier_sequence</field>
                <field name="code">res.partner.supplier</field>
                <field name="prefix">S</field>
                <field name="padding">5</field>
            </record>
    </data>
</openerp>

I get the numbering, but I have this error:

2013-04-15 12:41:07,379 4932 ERROR infinitechoice openerp.sql_db: bad query: ALTER TABLE "res_partner" ADD CONSTRAINT "res_partner_name_uniq_1" unique(n_client)
Traceback (most recent call last):
  File "/opt/openerp-7.0/openerp/sql_db.py", line 227, in execute
    res = self._obj.execute(query, params)
IntegrityError: could not create unique index "res_partner_name_uniq_1"
DETAIL:  Key (n_client)=(/) is duplicated.

2013-04-15 12:41:07,379 4932 WARNING infinitechoice openerp.osv.orm.schema: Table 'res_partner': unable to add 'unique(n_client)' constraint !
 If you want to have it, you should update the records and execute manually:
ALTER TABLE "res_partner" ADD CONSTRAINT "res_partner_name_uniq_1" unique(n_client)
2013-04-15 12:41:07,384 4932 ERROR infinitechoice openerp.sql_db: bad query: ALTER TABLE "res_partner" ADD CONSTRAINT "res_partner_n_supplier_uniq" unique(n_supplier)
Traceback (most recent call last):
  File "/opt/openerp-7.0/openerp/sql_db.py", line 227, in execute
    res = self._obj.execute(query, params)
IntegrityError: could not create unique index "res_partner_n_supplier_uniq"
DETAIL:  Key (n_supplier)=(/) is duplicated.

2013-04-15 12:41:07,384 4932 WARNING infinitechoice openerp.osv.orm.schema: Table 'res_partner': unable to add 'unique(n_supplier)' constraint !
 If you want to have it, you should update the records and execute manually:
ALTER TABLE "res_partner" ADD CONSTRAINT "res_partner_n_supplier_uniq" unique(n_supplier)

Problably I'm doing something wrong, do you know what it is ?

Thanks

0
Avatar
Descartar
Avatar
Gustavo
Mejor respuesta

You already have data in the res_partner table, that's why you get the database error. Try removing the data or starting your sequence from a different number than 0

1
Avatar
Descartar
Anabela Damas
Autor

So is because of _defaults ? But without having the default value '/' I can get this to work...

Gustavo

check your data first, you already have data on your database. The error is a database error, not an OpenERP error

Anabela Damas
Autor

Yes I've "Your Company" and "Administrator", so I've to change the code to prevent the error... Do you how?

Gustavo

Yes, you need to modify the create and copy functions. When you assign the value to the vals variable, you need to add a constant value (such as 10) that represents the max value of the data already stored in your database

Anabela Damas
Autor

Sorry I didn't understand what you mean.

Anabela Damas
Autor

Thanks I alredy fix this

¿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
how to set unique number?
sequence constraint unique
Avatar
Avatar
1
mar 15
8602
Sequence Prefix
sequence
Avatar
0
feb 23
6163
How to customize the invoice,bill and journal name sequence
sequence
Avatar
0
ene 23
95
What is the best (correct) way to create sequence ? py or xml? Resuelto
sequence
Avatar
Avatar
1
oct 22
5039
Deleted a sequence
sequence
Avatar
0
abr 22
3461
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