# 混入类,提供Model实例to_dict方法
class ModelMixin(object):
__slots__ = ()
def to_dict(self, excludes: tuple = None, selects: tuple = None) -> dict:
if not hasattr(self, '_meta'):
raise TypeError(
'<%r> does not a django.db.models.Model object.' % self)
elif selects:
return {f: getattr(self, f) for f in selects}
elif excludes:
return {f.attname: getattr(self, f.attname) for f in self._meta.fields if f.attname not in excludes}
else:
return {f.attname: getattr(self, f.attname) for f in self._meta.fields}
def update_by_dict(self, data):
for key, value in data.items():
setattr(self, key, value)
self.save()
class App(models.Model, ModelMixin):
name = models.CharField(max_length=50)
key = models.CharField(max_length=50, unique=True)
desc = models.CharField(max_length=255, null=True)
rel_apps = models.TextField(null=True)
rel_services = models.TextField(null=True)
sort_id = models.IntegerField(default=0, db_index=True)
created_at = models.CharField(max_length=20, default=human_datetime)
created_by = models.ForeignKey(User, on_delete=models.PROTECT)
def to_dict(self, *args, **kwargs):
tmp = super().to_dict(*args, **kwargs)
tmp['rel_apps'] = json.loads(self.rel_apps) if self.rel_apps else []
tmp['rel_services'] = json.loads(
self.rel_services) if self.rel_services else []
return tmp
def __repr__(self):
return f'<App {self.name!r}>'
class Meta:
db_table = 'apps'
ordering = ('-sort_id',)
项目地址:https://gitee.com/openspug/spug/
标签:return,一个,self,attname,models,dict,rel,思路,序列化 From: https://www.cnblogs.com/dreammooncy/p/18185727