[Django]-Why does Django with sqlite not insert unique constraint into the database schema?


You write the constraint directly in the Meta class which has no effect. You instead need to write it in a list on the attribute constraints [Django docs] in the Meta class:

from django.db import models

class Fruit(models.Model):
    fruit_id = models.IntegerField(primary_key=True)
    fruit_type = models.CharField(max_length=64, default='', blank=True, null=False)
    fruit_name = models.CharField(max_length=128, default='', blank=True, null=False)
    class Meta:
        constraints = [
            models.UniqueConstraint(fields=['fruit_type', 'fruit_name'], name='unique_fruit_type_name')
        db_table = 'fruit'

Note: Make sure to run python manage.py makemigrations and python manage.py migrate after making these changes.

Leave a comment