所以有一段时间在我的第一次迁移后,我决定将这些字段包含在内:
param (
$sessionUrl = "ftp://user:mypassword@example.com/",
$remotePath = "/path"
)
# Load WinSCP .NET assembly
Add-Type -Path "WinSCPnet.dll"
# Setup session options
$sessionOptions = New-Object WinSCP.SessionOptions
$sessionOptions.ParseUrl($sessionUrl)
# Connect
$session = New-Object WinSCP.Session
$session.Open($sessionOptions)
# Get list of files in the directory
$directoryInfo = $session.ListDirectory($remotePath)
# Select the most recent file
$latest =
$directoryInfo.Files |
Where-Object { -Not $_.IsDirectory } |
Sort-Object LastWriteTime -Descending |
Select-Object -First 1
# Any file at all?
if ($latest -eq $Null)
{
Write-Host "No file found"
}
else
{
Write-Host "The latest file is $latest"
}
进入我的一个模特。当我created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
它给了我
makemigrations
然后我将其改为
You are trying to add a non-nullable field 'created' to episode without a default; we can't do that (the database needs
something to populate existing rows).
再次尝试created = models.DateTimeField(auto_now_add=True, default=datetime.now)
后,它说makemigrations
好的,所以我继续前进并删除了auto_now_add
at_api.Episode.modified: (fields.E160) The options auto_now, auto_now_add, and default are mutually exclusive. Only one
of these options may be present.
我现在可以created = models.DateTimeField(default=datetime.now)
没有任何问题。然后我删除了makemigrations
并将其替换为default=datetime.now
,并再次迁移,没有任何问题。但是,我不禁觉得这可能不是最好的做事方式。我觉得项目后期可能会出现问题。
答案 0 :(得分:8)
我认为这里最好的做法是让这些字段可以为空。您的created
字段目前的含义是:“创建实例的时间,或我运行迁移时的任意时间。”表示缺少值的标准方法是NULL
,而不是任意值。
那就是说,如果你想使用一些任意值,你只需要告诉Django它是什么。通常makemigrations
为您提供了指示用于现有行的一次性值的选项 - 这是不是会发生?
更费力的方法是将字段声明为可空,然后创建数据迁移以填充所需的值,然后使其不可为空。你所做的基本上是简化版。除了created
的问题不是实际创建实例的时候,我认为它不会产生任何问题。
答案 1 :(得分:3)
我刚遇到了确切的问题。我使用Django 1.10。我读了Kevin的答案,当Django让我把它填充为datetime.now
字符串时,我试图设置默认值。
我感到很惊讶,因为对于那些字段,Django会自动询问您是否要使用datetime.now
作为默认值:
$ ./manage.py makemigrations
You are trying to add the field 'date_created' with 'auto_now_add=True' to projectasset without a default; the database needs something to populate existing rows.
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
You can accept the default 'timezone.now' by pressing 'Enter' or you can provide another value.
The datetime and django.utils.timezone modules are available, so you can do e.g. timezone.now
Type 'exit' to exit this prompt
[default: timezone.now] >>>
所以,我只是确认一下,一切似乎都运转良好!