问题描述
我在运行有几个条目的服务器中的应用程序中有一个模型。我需要添加一个 SlugField
,该模型唯一且不为null。 SlugField
将根据 trading_name
进行填充。我更改了模型以添加此新字段并修改了保存方法:
I have one model in my app running in a server with a few entries. I need to add a SlugField
, unique and not-null for this model. The SlugField
will be populated based on trading_name
. I've changed my model in order to add this new field and modified save method:
class Supplier(StatusModel):
SLUG_MAX_LENGTH = 210
slug = models.SlugField(unique=True, max_length=SLUG_MAX_LENGTH)
trading_name = models.CharField(max_length=200, verbose_name=_('trading name'))
...
def save(self, *args, **kwargs):
self.slug = orig = slugify(self.trading_name)[:Supplier.SLUG_MAX_LENGTH]
for x in itertools.count(1):
if not Supplier.objects.filter(slug=self.slug).exists():
break
# Truncate the original slug dynamically. Minus 1 for the hyphen.
self.slug = "%s-%d" % (orig[:Supplier.SLUG_MAX_LENGTH - len(str(x)) - 1], x)
self.full_clean()
super(Supplier, self).save(*args, **kwargs)
之后更改模型,我运行 manage.py makemigrations
并将此迁移作为输出:
After changing the model, I've run manage.py makemigrations
and got this migration as output:
class Migration(migrations.Migration):
dependencies = [
('opti', '0003_auto_20141226_1755'),
]
operations = [
migrations.AddField(
model_name='supplier',
name='slug',
field=models.SlugField(unique=True, default='', max_length=210),
preserve_default=False,
),
]
我无法运行 manage.py migration
,因为默认值由于唯一常量而无法使用。
I can't run manage.py migrate
because the default value wont work due to the unique constrant.
我的问题是:如何使用Django 1.7做到这一点?我需要应用模式更改并将当前条目保留在数据库中。
My question is: How can I do this with Django 1.7? I need to apply the schema change and keep the current entries in my database.
推荐答案
不幸的是,我没有找到答案,但是我可以创建一个解决方案:
Unfortunatelly, I found no answer but I could create one solution:
- 首先,我创建了一个迁移,该迁移允许slug字段可为空;
- 然后,我创建了另一个迁移,该迁移向模型中的每一行填充了适当的值;
- 然后是另一个迁移,在该列中添加了非空约束。 li>
- First I have created a migration that allows the slug field to be nullable;
- Then I have created another migration that populates the slug column with proper values to every row in the model;
- Then another migration which adds the not-null constraint in the column.
这篇关于使用已填充的模型添加非空且唯一的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!