django之自定义软删除Model的方法

  • 时间:
  • 浏览:21

硬删除

简朴的道,便是当履行删除操纵的时分,没有正实履行删除操纵,而是正在逻辑上删除1笔记录。如许做的益处是能够统计数据,能够停止规复操纵等等。

豫备常识

Managers

Managers 是django models 供给的1个用于供给数据库查询操纵的接心,对Django利用法式中的每一个model城市最少存正在1个Manager

具体:https://docs.djangoproject.com/en/dev/topics/db/managers/

django真现硬删除model

firstly,

from django.db import models
from django.db.models.query import QuerySet

# 自界说硬删除查询基类
class SoftDeletableQuerySetMixin(object):
  """
  QuerySet for SoftDeletableModel. Instead of removing instance sets
  its ``is_deleted`` field to True.
  """

  def delete(self):
    """
    Soft delete objects from queryset (set their ``is_deleted``
    field to True)
    """
    self.update(is_deleted=True)


class SoftDeletableQuerySet(SoftDeletableQuerySetMixin, QuerySet):
  pass


class SoftDeletableManagerMixin(object):
  """
  Manager that limits the queryset by default to show only not deleted
  instances of model.
  """
  _queryset_class = SoftDeletableQuerySet

  def get_queryset(self):
    """
    Return queryset limited to not deleted entries.
    """
    kwargs = {'model': self.model, 'using': self._db}
    if hasattr(self, '_hints'):
      kwargs['hints'] = self._hints

    return self._queryset_class(**kwargs).filter(is_deleted=False)


class SoftDeletableManager(SoftDeletableManagerMixin, models.Manager):
  pass

secondly,

# 自界说硬删除笼统基类
class SoftDeletableModel(models.Model):
  """
  An abstract base class model with a ``is_deleted`` field that
  marks entries that are not going to be used anymore, but are
  kept in db for any reason.
  Default manager returns only not-deleted entries.
  """
  is_deleted = models.BooleanField(default=False)

  class Meta:
    abstract = True

  objects = SoftDeletableManager()

  def delete(self, using=None, soft=True, *args, **kwargs):
    """
    Soft delete object (set its ``is_deleted`` field to True).
    Actually delete object if setting ``soft`` to False.
    """
    if soft:
      self.is_deleted = True
      self.save(using=using)
    else:
      return super(SoftDeletableModel, self).delete(using=using, *args, **kwargs)

class CustomerInfo(SoftDeletableModel):
  nid = models.AutoField(primary_key=True)
  category = models.ForeignKey("CustomerCategory", to_field="nid", on_delete=models.CASCADE, verbose_name='客户分类',
                 db_constraint=False)
  company = models.CharField(max_length=64, verbose_name="公司称号")

以上便是本文的全数内容,期望对各人的进修有所帮忙,也期望各人多多撑持剧本之家。