I've defined a class called Country that has a unique name field.
class Country(models.Model):
class Meta:
verbose_name_plural = "Countries"
name = models.CharField(max_length=100, unique=True, null=False)
def __unicode__(self):
return self.name
On the admin page, this behaves as I'd expect it to. Creating a country that is already in the database fails with the error "Country with this Name already exists.". Perfect.
When I try to test the same thing in the interactive prompt (manage.py shell
), no such error is given. Instead the duplicate object is just added to the database.
>>> from rack.models import Country
>>> usa = Country(name="United States of America")
>>> usa.save()
>>> canada = Country(name="United States of America")
>>> canada.save()
>>> canada.name
'United States of America'
>>> Country.objects.all()
[<Country: United States of America>, <Country: United States of America>]
I'm quite new to Django, can anyone enlighten me as to why the shell ignores the unique field?
Have you reset your DB table? My guess is that you defined the model previously without unique=True.
The docs say that unique is enforced at the admin level and the database level, which matches your symptoms! That is.. it works in admin, not in shell.
http://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.Field.unique