问题
I'm creating a schema migration with South 0.7.6 for my Django 1.4.3 project with enabled timezone support.
The schema migration includes adding a DateTimeField
(with auto_now=True
) on one table.
When creating the migration, South prompts me:
The field 'MyTable.my_field' 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
What's the correct one-off value to give here, if I don't care about this value for existing rows (I just want the migration to succeed without warnings)?
So far, I used datetime.datetime.utcnow()
. However, then I get the following when applying the migration:
C:\Python27\lib\site-packages\django\db\models\fields\__init__.py:808:
RuntimeWarning: DateTimeField received a naive datetime (2013-01-16 00:00:00)
while time zone support is active.
South does not seem to import pytz or the Django helper classes, so how can I give a timezone-aware default value here?
回答1:
Manually edit the migration file that South created and add:
from django.utils import timezone
Then find the field that you are adding in the migration file and set its default
to timezone.now()
.
回答2:
pytz can be used for making timezone-aware datetime objects. you can use the following in your migration file:
import pytz
cn_tz = pytz.timezone('Asia/Shanghai')
then in your model
self.gf('django.db.models.fields.DateTimeField')(auto_now=True, default=datetime.datetime.now(cn_tz), blank=True),
回答3:
I noticed when I ran migrations on dev machine, it was different than when I ran them on production.
My dev machine at the top of the file has
from south_utils import datetime_utils as datetime
where on production it generated
import datetime
By replacing the latter with the former, it solved my issue with no additional edits to the migration file.
来源:https://stackoverflow.com/questions/14362414/default-value-of-datetimefield-for-south-migration-in-django-project-with-activa