Zum Inhalt springen
Odoo Menü
  • Anmelden
  • Jetzt gratis testen
  • Apps
    Finanzen
    • Buchhaltung
    • Rechnungsstellung
    • Spesenabrechnung
    • Tabellenkalkulation (BI)
    • Dokumente
    • E-Signatur
    Vertrieb
    • CRM
    • Vertrieb
    • Kassensystem – Shop
    • Kassensystem – Restaurant
    • Abonnements
    • Vermietung
    Websites
    • Website-Builder
    • E-Commerce
    • Blog
    • Forum
    • Livechat
    • E-Learning
    Lieferkette
    • Lager
    • Fertigung
    • PLM
    • Einkauf
    • Wartung
    • Qualität
    Personalwesen
    • Mitarbeiter
    • Personalbeschaffung
    • Abwesenheiten
    • Mitarbeiterbeurteilung
    • Personalempfehlungen
    • Fuhrpark
    Marketing
    • Social Marketing
    • E-Mail-Marketing
    • SMS-Marketing
    • Veranstaltungen
    • Marketing-Automatisierung
    • Umfragen
    Dienstleistungen
    • Projekte
    • Zeiterfassung
    • Außendienst
    • Kundendienst
    • Planung
    • Termine
    Produktivität
    • Dialog
    • Genehmigungen
    • IoT
    • VoIP
    • Wissensdatenbank
    • WhatsApp
    Apps von Drittanbietern Odoo Studio Odoo Cloud-Plattform
  • Branchen
    Einzelhandel
    • Buchladen
    • Kleidergeschäft
    • Möbelhaus
    • Lebensmittelgeschäft
    • Baumarkt
    • Spielwarengeschäft
    Essen & Gastgewerbe
    • Bar und Kneipe
    • Restaurant
    • Fast Food
    • Gästehaus
    • Getränkehändler
    • Hotel
    Immobilien
    • Immobilienagentur
    • Architekturbüro
    • Baugewerbe
    • Immobilienverwaltung
    • Gartenarbeit
    • Eigentümervereinigung
    Beratung
    • Buchhaltungsfirma
    • Odoo-Partner
    • Marketingagentur
    • Anwaltskanzlei
    • Talentakquise
    • Prüfung & Zertifizierung
    Fertigung
    • Textil
    • Metall
    • Möbel
    • Speisen
    • Brauerei
    • Firmengeschenke
    Gesundheit & Fitness
    • Sportklub
    • Brillengeschäft
    • Fitnessstudio
    • Therapeut
    • Apotheke
    • Friseursalon
    Handel
    • Handyman
    • IT-Hardware & -Support
    • Solarenergiesysteme
    • Schuster
    • Reinigungsdienstleistungen
    • HLK-Dienstleistungen
    Sonstiges
    • Gemeinnützige Organisation
    • Umweltschutzagentur
    • Plakatwandvermietung
    • Fotostudio
    • Fahrrad-Leasing
    • Software-Händler
    Alle Branchen ansehen
  • Community
    Lernen
    • Tutorials
    • Dokumentation
    • Zertifizierungen
    • Schulung
    • Blog
    • Podcast
    Bildung fördern
    • Bildungsprogramm
    • Scale-Up! Planspiel
    • Odoo besuchen
    Software anfragen
    • Herunterladen
    • Editionen vergleichen
    • Releases
    Zusammenarbeiten
    • Github
    • Forum
    • Veranstaltungen
    • Übersetzungen
    • Partner werden
    • Dienstleistungen für Partner
    • Buchhaltungsfirma registrieren
    Services anfragen
    • Partner finden
    • Buchhalter finden
    • Einen Experten treffen
    • Implementierungsservices
    • Kundenreferenzen
    • Support
    • Upgrades
    Github Youtube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Eine Demo erhalten
  • Preiskalkulation
  • Hilfe

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

  • CRM
  • e-Commerce
  • Buchhaltung
  • Lager
  • PoS
  • Projekte
  • MRP
All apps
Sie müssen registriert sein, um mit der Community zu interagieren.
Alle Beiträge Personen Abzeichen
Stichwörter (Alle anzeigen)
odoo accounting v14 pos v15
Über dieses Forum
Sie müssen registriert sein, um mit der Community zu interagieren.
Alle Beiträge Personen Abzeichen
Stichwörter (Alle anzeigen)
odoo accounting v14 pos v15
Über dieses Forum
Hilfe

_sql_constraint not working

Abonnieren

Erhalten Sie eine Benachrichtigung, wenn es eine Aktivität zu diesem Beitrag gibt

Diese Frage wurde gekennzeichnet
debug
4 Antworten
185 Ansichten
Avatar
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
Avatar
Verwerfen
Codesphere Tech

Which version?

Avatar
Tran Thinh
Autor Beste Antwort

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.

0
Avatar
Verwerfen
Avatar
Ramiz Belim
Beste Antwort

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
Avatar
Verwerfen
Avatar
Cybrosys Techno Solutions Pvt.Ltd
Beste Antwort
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
Avatar
Verwerfen
Avatar
Kunjan Patel
Beste Antwort
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
Avatar
Verwerfen
Diskutieren Sie gerne? Treten Sie bei, statt nur zu lesen!

Erstellen Sie heute ein Konto, um exklusive Funktionen zu nutzen und mit unserer tollen Community zu interagieren!

Registrieren
Verknüpfte Beiträge Antworten Ansichten Aktivität
Webhook. How can i send webhook by execute code?
debug
Avatar
0
Nov. 25
5
Facing trouble with my appointment section
debug
Avatar
0
Okt. 25
791
ValueError: Wrong value for ir.ui.view.type: 'tree'in Odoo18 Gelöst
debug
Avatar
Avatar
1
Sept. 25
1496
Custom Route splitting return transfers into two different returns.
debug
Avatar
0
Aug. 25
1835
How can I import data without losing information?
debug
Avatar
Avatar
1
Juli 25
1719
Community
  • Tutorials
  • Dokumentation
  • Forum
Open Source
  • Herunterladen
  • Github
  • Runbot
  • Übersetzungen
Dienstleistungen
  • Odoo.sh-Hosting
  • Support
  • Upgrade
  • Individuelle Entwicklungen
  • Bildung
  • Buchhalter finden
  • Partner finden
  • Partner werden
Über uns
  • Unsere Firma
  • Markenwerte
  • Kontakt
  • Karriere
  • Veranstaltungen
  • Podcast
  • Blog
  • Kunden
  • Rechtliches • Datenschutz
  • Sicherheit
الْعَرَبيّة 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 ist eine Suite von Open-Source-Betriebsanwendungen, die alle Bedürfnisse Ihres Unternehmens abdecken: CRM, E-Commerce, Buchhaltung, Lager, Kassensystem, Projektmanagement etc.

Das einzigartige Wertversprechen von Odoo ist, dass es gleichzeitig sehr einfach zu bedienen und voll integriert ist.

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