Django问题记录¶
兼容 python2.x 和 python3.x¶
示例如下:
# coding:utf-8
from __future__ import unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible
class Article(models.Model):
title = models.CharField('标题', max_length=256)
content = models.TextField('内容')
pub_date = models.DateTimeField('发表时间', auto_now_add=True, editable = True)
update_time = models.DateTimeField('更新时间',auto_now=True, null=True)
def __str__(self):
return self.title
python_2_unicode_compatible 会自动做一些处理去适应python不同的版本,本例中的 unicode_literals 可以让python2.x 也像 python3 那个处理 unicode 字符,以便有更好地兼容性。
如果抛出错误 django.core.exceptions.AppRegistryNotReady: Models aren’t loaded yet¶
导入数据
import django
if django.VERSION >= (1, 7):#自动判断版本
django.setup()