django中ORM有三个类:
    Manager:模型管理器,其中Manager类实现了和数据库之间的操作,Manager类中从QuerySet类中拷贝了许多表级方法,通过这些方法实现数据库的查询,并且将查询到的结果封装成一个Queryset对象返回,然后通过Queryset对象中的表级方法可以获取到我们需要的数据,如果我们不满足于现有的表级方法,可以通过重写Manager实现。
    Queryset:查询结果集,同数据库的所有查询以及更新交互都是通过QuerySet来完成的。
    Model:模型类,实现与数据库表的字段映射。

    自定义Queryset
    重写Queryset的update和delete方法可以帮助我们记录数据库的更新和删除

    1. class BaseQuerySet(QuerySet):
    2. def update(self, **kwargs):
    3. # 重写QuerySet的update方法 记录数据库更新日志
    4. log_list = []
    5. for model in self:
    6. update_log = dict()
    7. name = model.__module__.split('.')[-1]
    8. update_log['table_name'] = name
    9. update_log[name + '_pk'] = model.pk
    10. update_before = {} # 更新之前
    11. update_after = {} # 更新之后
    12. for key, value in kwargs.items():
    13. if not hasattr(model, key):
    14. continue
    15. model_value = getattr(model, key)
    16. if isinstance(model_value, decimal.Decimal): # 取出的类型有可能mongodb无法存储
    17. update_before[key] = float(model_value)
    18. else:
    19. update_before[key] = model_value
    20. if isinstance(value, models.Model): # 判断key是否为外键
    21. value = value.pk
    22. update_after[key] = value
    23. if key == 'update_operator' or key == 'update_operator_id':
    24. update_log['update_operator'] = value
    25. if [i for i in log_handler.log.important_table if i.match(name)]:
    26. update_log['update_before_all_info'] = str(model_to_dict(model))
    27. update_log['update_before_info'] = str(update_before)
    28. update_log['update_after_info'] = str(update_after)
    29. update_log['operating'] = 'update'
    30. log_list.append(update_log)
    31. result = super(BaseQuerySet, self).update(**kwargs)
    32. log_handler.log.record_business_log(log_list)
    33. return result
    34. def delete(self):
    35. log_list = []
    36. for info in self:
    37. delete_log = dict()
    38. name = info.__module__.split('.')[-1]
    39. delete_log['table_name'] = name
    40. delete_log[name + '_pk'] = info.pk
    41. delete_info = dict()
    42. for k, v in info.__dict__.items():
    43. if k == '_state':
    44. continue
    45. v = mysql_conversion_mongo_utils.conversion(v)
    46. delete_info[k] = v
    47. delete_log['delete_info'] = delete_info
    48. delete_log['delete_datetime'] = datetime.now()
    49. delete_log['operating'] = 'delete'
    50. log_list.append(delete_log)
    51. log_handler.log.record_business_log(log_list=log_list)
    52. return super(BaseQuerySet, self).delete()

    自定义Manager
    可以自定义Manager类来实现自己的方法,简化数据库的DML操作

    1. class Manager(DjangoManager.from_queryset(BaseQuerySet)):
    2. """
    3. 继承 BaseQuerySet
    4. 将QuerySet的方法当参数传给了 Manager
    5. """
    6. pass
    7. class BaseManager(Manager):
    8. """
    9. 通用的orm管理器
    10. """
    11. def get_one_object(self, db_select=None, **kwargs):
    12. """
    13. base manager 获取一条数据
    14. :param db_select: 为数据库分离做准备
    15. :param kwargs: 查询条件 k=v
    16. :return:
    17. """
    18. try:
    19. k_obj = self.db_manager(db_select).get(**kwargs)
    20. except (ObjectDoesNotExist, MultipleObjectsReturned) as e:
    21. k_obj = None
    22. except Exception as e:
    23. print(e)
    24. raise EtError(type=EtDBError.read_error, value='获取一条数据连接数据库有误')
    25. return k_obj
    26. def create_one_object(self, create_info=None, db_select=None, **kwargs):
    27. """
    28. base manager 添加一个对象 判断传来的参数是否为该管理器对应模型类的字段
    29. :param db_select: 为数据库分离做准备
    30. :param kwargs: k=v
    31. :return:
    32. """
    33. create_info = create_info if type(create_info) == dict else dict()
    34. res_attr_list = self.__get_all_attr_list()
    35. kwg_copy = copy.deepcopy(create_info)
    36. # 如果不是管理器对应模型类的字段则删除
    37. for kw in create_info:
    38. if kw not in res_attr_list:
    39. kwg_copy.pop(kw)
    40. # 创建对象f
    41. try:
    42. k_obj = self.db_manager(db_select).model(**kwg_copy)
    43. k_obj.save(force_insert=True)
    44. except Exception as e:
    45. print(e)
    46. k_obj = None
    47. return k_obj
    48. def update_object(self, filters=None, excludes=None, updates=None, db_select=None, **kwargs):
    49. """
    50. base manager 根据条件更新数据库的参数
    51. update info
    52. :param filters: 查询条件
    53. :param db_select: 为数据库分离做准备
    54. :param exclude: 查询条件
    55. :param update: 更新的内容
    56. :return:
    57. """
    58. filters = filters if type(filters) == dict else dict()
    59. excludes = excludes if type(excludes) == dict else dict()
    60. updates = updates if type(updates) == dict else dict()
    61. if len(filters) == 0 and len(excludes) == 0:
    62. return None
    63. if len(updates) == 0:
    64. return None
    65. try:
    66. k_objects = self.db_manager(db_select).filter(**filters).exclude(**excludes).update(**updates)
    67. except Exception as e:
    68. print(e)
    69. k_objects = None
    70. return k_objects
    71. def get_filter_list(self, filters=None, excludes=None, order_by=('-pk',), db_select=None, **kwargs):
    72. """
    73. base manager 批量获取数据
    74. :param filters: 查询条件
    75. :param excludes: 取反条件
    76. :param db_select: 为数据库分离做准备
    77. :param order_by: 排序提交
    78. :param kwargs:
    79. :return:
    80. """
    81. filters = filters if type(filters) == dict else dict()
    82. excludes = excludes if type(excludes) == dict else dict()
    83. try:
    84. select_related = kwargs.pop('select_related')
    85. except KeyError as e:
    86. select_related = (None,)
    87. try:
    88. only = kwargs.pop('only')
    89. k_object_list = self.db_manager(db_select).filter(**filters).exclude(**excludes).order_by(*order_by).select_related(*select_related).only(*only)
    90. except KeyError as e:
    91. k_object_list = self.db_manager(db_select).filter(**filters).exclude(**excludes).order_by(*order_by).select_related(*select_related)
    92. except Exception as e:
    93. print(e)
    94. k_object_list = None
    95. return k_object_list
    96. def get_filter_values(self, q_objs=None, filters=None, e_q_objs=None, excludes=None, order_by=None, values=None, db_select=None):
    97. """
    98. wangge
    99. 只查询某些字段,获取到的是QuerySet,跨表查询用的是 Inner Join
    100. :param q_objs: 元组形式的查询条件
    101. :param filters: 字典形式的查询条件
    102. :param e_q_objs: 元组形式的排除查询条件
    103. :param excludes: 排除条件
    104. :param order_by: 排序条件
    105. :param values: 只查询的某些字段
    106. :param db_select:
    107. :return: 返回值是QuerySet,元素是字典,查询报错返回 None
    108. """
    109. filters = filters if isinstance(filters, dict) else dict()
    110. excludes = excludes if isinstance(excludes, dict) else dict()
    111. q_objs = tuple(q_objs) if isinstance(q_objs, (tuple, list, set)) else tuple()
    112. e_q_objs = tuple(e_q_objs) if isinstance(e_q_objs, (tuple, list, set)) else tuple()
    113. order_by = tuple(order_by) if isinstance(order_by, (tuple, list, set)) else tuple()
    114. values = tuple(values) if isinstance(values, (tuple, list, set)) else tuple()
    115. try:
    116. dict_list = self.db_manager(db_select).filter(*q_objs, **filters).exclude(*e_q_objs, **excludes).order_by(*order_by).values(*values)
    117. except Exception as e:
    118. print(e)
    119. dict_list = None
    120. return dict_list
    121. def get_filter_and_fuzzy_queries_list(self, filters=None, q_objs=(), e_q_objs=(), excludes=None, order_by=None, db_select=None, **kwargs):
    122. """
    123. 过滤出查询结果后,对结果进行模糊查询,再将结果返回
    124. :param filters: 过滤条件 --> 字典
    125. :param excludes: 排除条件 --> 字典
    126. :param q_objs: 查询条件 --> Q对象
    127. :param e_q_objs: 排除条件 --> Q对象
    128. :param order_by: 排序条件
    129. :param db_select: 数据库选择
    130. :param kwargs: 预留参数
    131. :return:
    132. """
    133. filters = filters if type(filters) == dict else dict()
    134. excludes = excludes if isinstance(excludes, dict) else dict()
    135. if not order_by:
    136. order_by = ('-pk',)
    137. try:
    138. k_object_list = self.db_manager(db_select).filter(**filters).filter(*q_objs).exclude(*e_q_objs, **excludes).order_by(*order_by)
    139. except Exception as e:
    140. print(e)
    141. k_object_list = None
    142. return k_object_list
    143. def get_count(self, condition=None, db_select=None):
    144. """
    145. manager 获取count
    146. :param db_select: 为数据库分离做准备
    147. :param condition:
    148. :return:
    149. """
    150. condition = condition if type(condition) == dict else dict()
    151. try:
    152. count = self.db_manager(db_select).filter(**condition).count()
    153. except Exception as e:
    154. count = None
    155. print(e)
    156. return count
    157. def delete_mul_obj(self, filters, excludes, db_select, **kwargs):
    158. """
    159. 删除数据库
    160. :param filters:
    161. :param excludes:
    162. :param db_select:
    163. :param kwargs:
    164. :return:
    165. """
    166. filters = filters if type(filters) == dict else dict()
    167. excludes = excludes if type(excludes) == dict else dict()
    168. if len(filters) == 0 and len(excludes) == 0:
    169. return None
    170. try:
    171. res = self.db_manager(db_select).filter(**filters).exclude(**excludes).delete()
    172. except Exception as e:
    173. print(e)
    174. res = None
    175. return res
    176. def del_info(self, condition, db_select=None, **kwargs):
    177. """
    178. 删除一些临时数据
    179. :param condition:
    180. :param db_select:
    181. :param kwargs:
    182. :return:
    183. """
    184. condition = condition if type(condition) == dict else dict()
    185. if len(condition) == 0:
    186. return 0
    187. try:
    188. result = self.db_manager(db_select).filter(**condition).delete()
    189. result = result[0]
    190. except Exception as e:
    191. print(e)
    192. result = 0
    193. return result
    194. class BaseModel(models.Model):
    195. objects = BaseManager()
    196. def __getitem__(self, item):
    197. if hasattr(self, item):
    198. return getattr(self, item)
    199. else:
    200. return None
    201. class Meta:
    202. abstract = True


    参考:https://www.jianshu.com/p/822e67e2f9d6