Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

393
Views
Django: agregue un índice único en expresiones en postgres

Considere el modelo django -

 class Students(models.Model) id = models.BigAutoField(primary_key=True) scoreA = models.CharField(null=True, max_length=15) scoreB = models.CharField(null=True, max_length=15)

Estoy buscando agregar este índice único.

 create unique index unq_idx on students ((case when scoreA is not NULL then scoreA else '' end), (case when scoreB is not NULL then scoreB else '' end));

¿Cómo lo agrego a través de Django ORM?

Estoy usando Django 3.1 con postgres 12.1

El caso de uso es tener una restricción única sobre los dos campos que no permite múltiples valores NULL ( Enlace )

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

A partir de django-4.0 , será posible crear restricciones funcionales únicas [Django-doc] . En ese caso, puede definir dicha restricción con:

 from django.db.models import UniqueConstraint , Value from django.db.models.functions import Coalesce class Students(models.Model) id = models.BigAutoField(primary_key=True) scoreA = models.CharField(null=True, max_length=15) scoreB = models.CharField(null=True, max_length=15) class Meta: constraints = [ UniqueConstraint( Coalesce('scoreA', Value('')), Coalesce('scoreB', Value('')) , name='unique_score_combo') ]
over 4 years ago · Santiago Trujillo Report

0

Lo hice funcionar con Django 3.2 usando Index.expressions y el ajuste UniqueIndex de django-postgres-extra

 class Students(models.Model) id = models.BigAutoField(primary_key=True) scoreA = models.CharField(null=True, max_length=15) scoreB = models.CharField(null=True, max_length=15) class Meta: indexes = [ UniqueIndex( Case(When(scoreA__isnull=False, then=F('scoreA')), default=Value('')), Case(When(scoreB__isnull=False, then=F('scoreB')), default=Value('')), name='unique_idx'), ]
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!