开发者

Django unique field ignored in interactive shell

开发者 https://www.devze.com 2023-01-30 23:19 出处:网络
I\'ve defined a class called Country that has a unique name field. class Country(models.Model): class Meta:

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, t开发者_如何学JAVAhis 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


What database are you using? If you are using sqlite and South, there is a bug which doesn't allow adding unique constraints so sqlite tables.

If that's the case, it may be that the admin form enforces the uniqueness, so the check never even gets to the database, but when you do it from the command line, it's relying on the database to enforce uniqueness (which sqlite doesn't do in this case).


Are you sure the Country you're loading from rack.models is using the version you think it is? I'd check the __file__ on it and make sure it's not using some cached version of it. Or if you modify the model after it's imported it wouldn't necessarily trip that.

unique should enforce uniqueness at both the model and the database layer

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号