2👍
✅
Got it working with Django 3.2 using Index.expressions and the UniqueIndex tweak from 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'),
]
3👍
As of django-4.0, it will be possible to make functional unique constraints [Django-doc]. In that case you can define such constraint with:
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')
]
- [Django]-Django — new field: How to set default callable for existing objects
- [Django]-Removing Foreign Key
- [Django]-Import parent module from submodule
- [Django]-NameError: name 'RegexValidator' is not defined
Source:stackexchange.com