Skip to Content
Odoo Menu
  • Prisijungti
  • Išbandykite nemokamai
  • Programėlės
    Finansai
    • Apskaita
    • Pateikimas apmokėjimui
    • Sąnaudos
    • Skaičiuoklė (BI)
    • Dokumentai
    • Pasirašymas
    Pardavimai
    • CRM
    • Pardavimai
    • Kasų sistema - Parduotuvė
    • Kasų sistema - Restoranas
    • Prenumeratos
    • Nuoma
    Svetainės
    • Svetainių kūrėjimo įrankis
    • El. Prekyba
    • Internetinis Tinklaraštis
    • Forumas
    • Tiesioginis pokalbis
    • eMokymasis
    Tiekimo grandinė
    • Atsarga
    • Gamyba
    • PLM
    • Įsigijimai
    • Priežiūra
    • Kokybė
    Žmogaus ištekliai
    • Darbuotojai
    • Įdarbinimas
    • Atostogos
    • Įvertinimai
    • Rekomendacijos
    • Transporto priemonės
    Rinkodara
    • Socialinė rinkodara
    • Rinkodara el. paštu
    • SMS rinkodara
    • Renginiai
    • Rinkodaros automatizavimas
    • Apklausos
    Paslaugos
    • Projektas
    • Darbo laiko žiniaraščiai
    • Priežiūros tarnyba
    • Pagalbos tarnyba
    • Planavimas
    • Rezervacijos
    Produktyvumas
    • Diskucija
    • Patvirtinimai
    • IoT
    • VoIP
    • Žinių biblioteka
    • WhatsApp
    Trečiųjų šalių programos Odoo Studija Odoo debesijos platforma
  • Pramonės šakos
    Mažmeninė prekyba
    • Knygynas
    • Drabužių parduotuvė
    • Baldų parduotuvė
    • Maisto prekių parduotuvė
    • Techninės įrangos parduotuvė
    • Žaislų parduotuvė
    Food & Hospitality
    • Barai ir pub'ai
    • Restoranas
    • Greitasis maistas
    • Guest House
    • Gėrimų platintojas
    • Hotel
    Nekilnojamasis turtas
    • Real Estate Agency
    • Architektūros įmonė
    • Konstrukcija
    • Estate Managament
    • Sodininkauti
    • Turto savininkų asociacija
    Konsultavimas
    • Accounting Firm
    • Odoo Partneris
    • Marketing Agency
    • Teisinė firma
    • Talentų paieška
    • Auditai & sertifikavimas
    Gamyba
    • Textile
    • Metal
    • Furnitures
    • Maistas
    • Brewery
    • Įmonių dovanos
    Sveikata & Fitnesas
    • Sporto klubas
    • Akinių parduotuvė
    • Fitneso Centras
    • Sveikatos praktikai
    • Vaistinė
    • Kirpėjas
    Trades
    • Handyman
    • IT įranga ir palaikymas
    • Saulės energijos sistemos
    • Shoe Maker
    • Cleaning Services
    • HVAC Services
    Kiti
    • Nonprofit Organization
    • Aplinkos agentūra
    • Reklaminių stendų nuoma
    • Fotografavimas
    • Dviračių nuoma
    • Programinės įrangos perpardavėjas
    Browse all Industries
  • Bendrija
    Mokykitės
    • Mokomosios medžiagos
    • Dokumentacija
    • Sertifikatai
    • Mokymai
    • Internetinis Tinklaraštis
    • Tinklalaidės
    Skatinkite švietinimą
    • Švietimo programa
    • Scale Up! Verslo žaidimas
    • Aplankykite Odoo
    Gaukite programinę įrangą
    • Atsisiųsti
    • Palyginkite versijas
    • Leidimai
    Bendradarbiauti
    • Github
    • Forumas
    • Renginiai
    • Vertimai
    • Tapkite partneriu
    • Services for Partners
    • Registruokite jūsų apskaitos įmonę
    Gaukite paslaugas
    • Susiraskite partnerį
    • Susirask buhalterį
    • Susitikti su konsultantu
    • Diegimo paslaugos
    • Klientų rekomendavimas
    • Palaikymas
    • Atnaujinimai
    Github Youtube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Gaukite demo
  • Kainodara
  • Pagalba

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

  • CRM
  • e-Commerce
  • Apskaita
  • Atsarga
  • PoS
  • Projektas
  • MRP
All apps
You need to be registered to interact with the community.
All Posts People Badges
Žymos (View all)
odoo accounting v14 pos v15
About this forum
You need to be registered to interact with the community.
All Posts People Badges
Žymos (View all)
odoo accounting v14 pos v15
About this forum
Pagalba

_sql_constraint not working

Prenumeruoti

Get notified when there's activity on this post

This question has been flagged
debug
3 Replies
225 Rodiniai
Portretas
Tran Thinh

Hello,
I am new to Odoo and try to study some Odoo Framework 101 (the estate model) I cam across chapter 10 and play around with constraint. The api.constrains works ok but the _sql_constraints/_sql_constrains does not work at all.
from odoo import fields, models, api, exceptions


class EstatePropertyTag(models.Model):

    _name = "estate.property.tag"

    _description = "Real Estate Tag"

    name = fields.Char("Tag Name", required=True)


    '''@api.constrains('name')

    def _check_tag(self):

        for record in self:

            # Search for any OTHER record ('id', '!=', record.id)

            # that has the SAME name ('name', '=', record.name)

            domain = [('name', '=', record.name), ('id', '!=', record.id)]

            count = self.search_count(domain)

            if count > 0:

                raise exceptions.UserError("Tag name must be unique")'''


    _sql_constraints = [('unique_name', 'UNIQUE(name)', 'name must be unique!'),]

I try to restart, delete record, update module but nothing work, Does anyone have any insights ? Thanks in advance.

0
Portretas
Atmesti
Codesphere Tech

Which version?

Tran Thinh
Autorius

Don't know why Odoo Forum not letting me reply to your comments, still thanks you guys a lot for the help. Since I fork the github odoo repo directly so I get the newest Odoo 19. Thus that _sql_constrain does not work. So Ramiz Belim has the correct answer for my case.

Portretas
Ramiz Belim
Best Answer

Hello,

I think the confusion comes from the Odoo version you are using. Let me clarify:

In Odoo versions ≤18:

  • _sql_constraints is still supported and works for database-level constraints like uniqueness or check constraints.

  • Example in older versions:
    _sql_constraints = [

  •    ('unique_name', 'UNIQUE(name)', 'Name must be unique!'),

  • ]

In Odoo 19:

  • ​_sql_constraints has been removed. It no longer works.
  • ​You must use the new models.Constraint API to define database constraints.

​Example in Odoo 19:

from odoo import models, fields

class MyModel(models.Model):
    _name = 'my.model'
    _description = 'My Model'

    name = fields.Char(required=True)
    code = fields.Char(required=True)
    payment_type = fields.Selection([('cash','Cash'),('card','Card')])

    # Unique constraint on single field
    _name_unique = models.Constraint(
        'unique (name)',
        'Name must be unique!'
    )

    # Unique constraint on multiple fields
    _code_payment_unique = models.Constraint(
        'unique (code, payment_type)',
        'The combination of Code and Payment Type must be unique!'

    )



0
Portretas
Atmesti
Portretas
Cybrosys Techno Solutions Pvt.Ltd
Best Answer
Hi,

The SQL constraint itself is correct, but it fails because PostgreSQL cannot create a UNIQUE index when duplicate tag names already exist in the database. When duplicates are present, Odoo does not show an error, PostgreSQL silently refuses to apply the constraint, so the model loads normally, but the UNIQUE rule is never actually enforced. Even if you restart the server or update the module, the constraint will never activate until duplicates are removed.

You can confirm this by checking the table for duplicate names and inspecting whether the UNIQUE index exists at the database level. If duplicates are found, they must be deleted or renamed before upgrading the module again. After cleaning the data, running a proper module upgrade will allow PostgreSQL to create the UNIQUE constraint normally. Once the constraint is successfully added, it will automatically prevent duplicate tag names without needing the Python @api.constrains check.

Hope it helps

0
Portretas
Atmesti
Portretas
Kunjan Patel
Best Answer
Hello Tran Thinh
I hope you are doing well

SQL constraints are only created when the table is first created - Odoo doesn't add them to existing tables automatically.

To fix: Either manually add via PostgreSQL: ALTER TABLE estate_property_tag ADD CONSTRAINT unique_name UNIQUE(name); or drop the table and reinstall the module (dev only). 
Also ensure no duplicate values ​​already exist in the name column - PostgreSQL will reject the constraint if duplicates are found. After fixing, restart Odoo and upgrade the module.

I hope this information helps you

Thanks & Regards
Kunjan Patel
0
Portretas
Atmesti
Enjoying the discussion? Don't just read, join in!

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

Registracija
Related Posts Replies Rodiniai Veikla
Webhook. How can i send webhook by execute code?
debug
Portretas
0
lapkr. 25
5
Facing trouble with my appointment section
debug
Portretas
0
spal. 25
792
ValueError: Wrong value for ir.ui.view.type: 'tree'in Odoo18 Solved
debug
Portretas
Portretas
1
rugs. 25
1499
Custom Route splitting return transfers into two different returns.
debug
Portretas
0
rugp. 25
1837
How can I import data without losing information?
debug
Portretas
Portretas
1
liep. 25
1721
Bendrija
  • Mokomosios medžiagos
  • Dokumentacija
  • Forumas
Atvirasis kodas
  • Atsisiųsti
  • Github
  • Runbot
  • Vertimai
Paslaugos
  • Odoo.sh talpinimas
  • Palaikymas
  • Atnaujinti
  • Pritaikytas programavimo kūrimas
  • Švietimas
  • Susirask buhalterį
  • Susiraskite partnerį
  • Tapkite partneriu
Apie mus
  • Mūsų įmonė
  • Prekės ženklo turtas
  • Susisiekite su mumis
  • Darbo pasiūlymai
  • Renginiai
  • Tinklalaidės
  • Internetinis Tinklaraštis
  • Klientai
  • Teisinis • Privatumas
  • Saugumas
الْعَرَبيّة 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 yra atvirojo kodo verslo programų rinkinys, kuris apima visas įmonės poreikius: CRM, El. Prekybą, Apskaitą, Atsargų, Kasų sistemą, Projektų valdymą ir kt.

Unikali Odoo vertės pasiūla – būti tuo pačiu metu labai lengvai naudojama ir visiškai integruota sistema.

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