1
期间只调用一次我创建了以下基本的Django模型:默认值的Django迁移
import string
import random
from django.db import models
def create_short_url():
size = 6
chars = string.ascii_uppercase + string.digits
url = ''.join(random.choice(chars) for _ in range(size))
print("\nSHORT_URL:%s\n" % url)
return url
class ShortURL(models.Model):
url = models.CharField(max_length=220,)
shortcode = models.CharField(max_length=15, unique=True, default=create_short_url)
def __str__(self):
return str(self.url)
首先,我只是编码的url
领域。然后我添加了shortcode
字段并提供了一个函数来调用以创建默认唯一值。 Django的文档说
如果可调用,每次创建新对象时都会调用它。
不幸的是,在运行迁移时,我看到仅生成一个短url和以下异常:
$ python manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, sessions, shortener
Running migrations:
Applying shortener.0002_auto_20161107_1529...
SHORT_URL:43AY7G
Traceback (most recent call last):
File "/home/user/django1.10/py3/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/home/user/django1.10/py3/lib/python3.5/site-packages/django/db/backends/sqlite3/base.py", line 337, in execute
return Database.Cursor.execute(self, query, params)
sqlite3.IntegrityError: UNIQUE constraint failed: shortener_shorturl.shortcode
缺什么呼吁每个条目功能被迁移?
参见[迁移是添加独特的领域(https://docs.djangoproject.com/en/1.10/howto/writing-migrations/#migrations-that-add-唯一字段)来修复错误。 – knbk
谢谢,这似乎是它必须完成的方式。无论如何,我们无法在一个“自动魔法”步骤中做到这一点有点令人惊讶。 ?!? – samb