予。假设您有以下型号:
class Knight(models.Model):
name = models.CharField(max_length=100)
of_the_round_table = models.BooleanField()
II。现在,您将此模型添加到南方的schemamigration并迁移:
python manage.py schemamigration myapp --initial
python manage.py migrate myapp
III。您在Knight
表中创建了一个条目:
>>> jason = Knight.objects.get(name=”Jason”)
这里没有什么不寻常的,只是常规的例程。但请注意以下事项。
IV-A。添加新模型字段(CharField
):
class Knight(models.Model):
name = models.CharField(max_length=100)
of_the_round_table = models.BooleanField()
surname = models.CharField(max_length=100) # +
V-甲。为这个新字段编写一个schemamigration:
$ python manage.py schemamigration myapp --auto
? The field 'Knight.surname' does not have a default specified, yet is NOT NULL.
? Since you are adding this field, you MUST specify a default
? value to use for existing rows. Would you like to:
? 1. Quit now, and add a default to the field in models.py
? 2. Specify a one-off value to use for existing columns now
BUT
现在让我们再次尝试步骤IV和V,但使用BooleanField
代替CharField
IV-B。添加新模型字段(BooleanField
):
class Knight(models.Model):
name = models.CharField(max_length=100)
of_the_round_table = models.BooleanField()
has_sword = models.BooleanField() # +
V-B中。为这个新字段编写一个schemamigration:
$ python manage.py schemamigration myapp --auto
+ Added field has_sword on registration.Knight
Created 0005_auto__add_field_knight_has_sword.py. You can now apply this migration with: ./manage.py migrate registration
Q1:为什么我添加BooleanField
(V-B
)的输出与添加CharField
(V-A
)的输出不同,即使{{ 3}}这两个字段默认为null=False
?
Q2:当你将BooleanField
应用于模型时,你应该如何知道哪些字段会提供类似CharField
的输出以及哪些字段会产生类似python manage.py schemamigration myapp --auto
的输出在特定情况下?
我正在使用SQlite
作为RDBMS和Django 1.4
btw。
答案 0 :(得分:3)
这是因为在Django 1.5版本中,BooleanField
使用False
作为隐式默认值。那是going to change in Django 1.6。
因此,虽然您的CharField
没有指定默认值,但强制南方提示您,但BooleanField
确实有默认值,即使是隐式值。