0

I have below model:

class Property(models.Model):
    job = models.ForeignKey(Job, on_delete=models.CASCADE)
    app = models.ForeignKey(App, on_delete=models.CASCADE)
    name = models.CharField(max_length=120)
    value = models.CharField(max_length=350, blank=True)
    description = models.TextField(blank=True)
    pub_date = models.DateTimeField('date_published', default=timezone.now)

    class Meta:
        verbose_name_plural = "properties"
        unique_together = (('value', 'name'),)

    def __str__(self):
        return self.name

When I try to create a Property object in admin page (I'm using Django Suit) with name/value which are already exist I get the exception: "Property with this Value and Name already exists." So it works perfect.

But in manage.py shell:

>>>from myapp.models import App, Property, Job
>>>from django.shortcuts import get_object_or_404
>>>app = get_object_or_404(App, app_name='BLABLA')
>>>job = get_object_or_404(Job, job_name='BLABLA2')
>>> Property.objects.create(job=job, app=app, name='1', value='1')
<Property: 1>
>>> Property.objects.create(job=job, app=app, name='1', value='1')
<Property: 1>

In this case I do not get any exceptions and objects are added in database.

I tried makemigrations, migrate and migrate --run-syncdb. Django 1.9.12, sqlite3

1 Answers1

2

The unique constraints are enforced at database level. You're not getting any error probably because SQLite doesn't support this type of constraint. You cannot add constraint to existing table in SQLite. If you're in early development stage, drop the table and recreate it with updated constraints. Then it should work fine in shell.

Check SQLite alter table docs for allowed updates on an existing table.

The admin form throws error because it checks uniqueness by itself without relying on database constraints.

narendra-choudhary
  • 4,582
  • 4
  • 38
  • 58