我有一个AJAX处理过的视图,它接收几条信息,其中两条是unicode datetime值。
但是,当我尝试直接从对象访问日期时间值(开始/结束)时,它似乎仍然是unicode。
我以为保存转换为datetime?
lid = int(postdata['lid'])
location = Group.objects.get(id=lid)
pgid = int(postdata['pgid'])
program = Group.objects.get(id=pgid)
start = postdata['start']
end = postdata['end']
eid = int(postdata['eid'])
creator = Employee.objects.get(id=eid)
description = postdata['description']
shift = ReliefShift()
shift.start = start
shift.end = end
shift.creator = creator
shift.description = description
shift.location = location
shift.program = program
shift.save()
alertModule = 'Relief Shifts Available'
alertMessage = 'A new relief shift has been posted for {0} from {1} to {2}. Visit the <a href="/staff/program/open-relief-shifts/">Relief Shifts page</a> for more details and to sign up.'.format(shift.location, shift.start.strftime('%b %d @ %I:%M%p'), shift.end.strftime('%b %d @ %I:%M%p'))
答案 0 :(得分:1)
调用shift.save()
会将日期时间保存到数据库,但不会更新shift
。保存后,您可以通过调用refresh_from_db
shift.start = <unicode string>
shift.save()
# At this point, shift.start will still be a string
shift.refresh_from_db()
# refresh_from_db is new in Django 1.8. In early versions you would do:
shift = Shift.objects.get(pk=shift.pk)
直接从帖子数据中读取值并不是一种好习惯。最好使用form或model form。 Django将负责将值转换为datetime对象,如果您使用的是模型表单,则可以从form.cleaned_data
或实例访问日期时间。