Skip to content

Instantly share code, notes, and snippets.

@fengxuway
Created August 24, 2016 02:01
Show Gist options
  • Save fengxuway/e6bb429413c304561e0573c1f90488aa to your computer and use it in GitHub Desktop.
Save fengxuway/e6bb429413c304561e0573c1f90488aa to your computer and use it in GitHub Desktop.
Django框架的Model基类, 提供可将Model对象转为字典的方法。
class BaseModel(models.Model):
create_time = models.DateTimeField(verbose_name=u'创建时间', auto_now_add=True)
update_time = models.DateTimeField(verbose_name=u'更新时间', auto_now=True)
objects = BaseManager()
def get_type(self):
return self.__class__.__name__
def to_dict(self):
d = {}
for _attr in self._meta.fields:
attr = _attr.name
val = getattr(self, attr)
if attr == 'password':
continue
if isinstance(val, datetime.datetime):
# 转换时区(数据库存储UTC时间)
val = val.replace(tzinfo=pytz.UTC).astimezone(pytz.timezone(settings.TIME_ZONE))
d[attr] = val.strftime('%Y-%m-%d %H:%M')
elif isinstance(val, datetime.date):
d[attr] = val.strftime('%Y-%m-%d')
elif isinstance(val, BaseModel):
d[attr] = val.to_dict()
else:
d[attr] = getattr(self, attr)
return d
class Meta:
abstract = True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment