39👍
✅
Django 2.2 and later
As of version 2.2 Django supports declarative partial unique indexes on databases that support them (PostgreSQL and SQLite). So you could do something like:
from django.db.models import Model, Q, UniqueConstraint
class Post(Model):
...
class Meta:
constraints = [
UniqueConstraint(
fields=["title", "blog", "category"],
name="idx1",
condition=Q(category__isnull=False)),
UniqueConstraint(
fields=["title", "blog"],
name="idx2",
condition=Q(category__isnull=True)),
]
Django 2.1 and earlier
In older versions you need to do this with migrations. First create a new, empty migration file:
python manage.py makemigrations --empty yourappname
Then, for each index add an appropriate RunSQL
line:
operations = [
migrations.RunSQL("CREATE UNIQUE INDEX..."),
migrations.RunSQL("CREATE UNIQUE INDEX..."),
]
Finally, run migrate
.
-1👍
You could just provide an unique_together
like so:
class Post(models.Model):
title = models.CharField(max_length=200)
blog = models.ForeignKey(Blog)
category = models.ForeignKey(Category, null=True, blank=True)
class Meta:
unique_together = ("title", "blog", "category")
NULLs for category will work how you want in that if not set then title/blog has to be unique.
https://docs.djangoproject.com/en/1.8/ref/models/options/#unique-together
- Is there a command for creating an app using cookiecutter-django?
- How to download a filefield file in django view
- Django is very slow on my machine
Source:stackexchange.com