无法为Django DateTimeField()分配None

时间:2016-11-02 10:25:35

标签: python django

我可以判断这是一个错误吗? DateTimeField继承自DateField,它可以是可选的

我看过: How to make Django's DateTimeField optional? How can I make my model fields optional in Django?

models.py

Import-Module Azure.Storage
. .\MyDSC-Class.ps1

在终端

class Circuit(SoftDeletionModel):
    ...
    created_datetime = models.DateTimeField(default=timezone.now)
    updated_datetime = models.DateTimeField(auto_now=True)
    expiry_datetime = models.DateTimeField(null=True, blank=True, default=None)

migration_file.py

$ python -B manage.py makemigrations --settings=config.settings.docker
apps.circuits is ready
apps.circuits_networkdevices is ready
apps.core is ready
apps.customers is ready
apps.networkdevices is ready
apps.networkscripts is ready
apps.portal is ready
apps.bod is ready
apps.scheduler is ready
You are trying to add a non-nullable field 'updated_datetime' to circuit without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:
 1) Provide a one-off default now (will be set on all existing rows)
 2) Quit, and let me add a default in models.py
Select an option: 1
Please enter the default value now, as valid Python
The datetime and django.utils.timezone modules are available, so you can do e.g. timezone.now()
>>> None
Migrations for 'circuits':
  0022_auto_20161102_1714.py:
    - Add field expiry_datetime to circuit
    - Add field updated_datetime to circuit

错误Django:

# -*- coding: utf-8 -*-
# Generated by Django 1.9.9 on 2016-11-02 10:14
from __future__ import unicode_literals

from django.db import migrations, models


class Migration(migrations.Migration):

    dependencies = [
        ('circuits', '0021_auto_20161102_1653'),
    ]

    operations = [
        migrations.AddField(
            model_name='circuit',
            name='expiry_datetime',
            field=models.DateTimeField(blank=True, default=None, null=True),
        ),
        migrations.AddField(
            model_name='circuit',
            name='updated_datetime',
            field=models.DateTimeField(auto_now=True, default=None),
            preserve_default=False,
        ),
    ]

错误Postgres:

django.db.utils.IntegrityError: column "updated_datetime" contains null values

规格:

postgres_1       | ERROR:  column "expiry_datetime" contains null values
postgres_1       | STATEMENT:  ALTER TABLE "circuits_circuit" ADD COLUMN "expiry_datetime" timestamp with time zone NOT NULL

2 个答案:

答案 0 :(得分:2)

你误解了auto_now做了什么

  

每次保存对象时自动将字段设置为现在。

您仍然需要使用null=True

指定有效的默认值或允许空值

答案 1 :(得分:1)

您无法将None分配给updated_datetime,因为您尚未在模型中设置null=True

您已经创建了一个迁移,告诉django在添加字段时遇到circuit表中的现有行时该怎么做但与能够执行该操作的行不同。

迁移要求的默认值不会检查是否允许使用该值,它相信您知道自己在做什么。

在迁移中使用datetime.now()而不是None