欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

django之自定義軟刪除Model的方法

 更新時(shí)間:2019年08月14日 16:10:28   作者:我愛(ài)學(xué)python  
這篇文章主要介紹了django之自定義軟刪除Model的方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧

軟刪除

簡(jiǎn)單的說(shuō),就是當(dāng)執(zhí)行刪除操作的時(shí)候,不正真執(zhí)行刪除操作,而是在邏輯上刪除一條記錄。這樣做的好處是可以統(tǒng)計(jì)數(shù)據(jù),可以進(jìn)行恢復(fù)操作等等。

預(yù)備知識(shí)

Managers

Managers 是django models 提供的一個(gè)用于提供數(shù)據(jù)庫(kù)查詢操作的接口,對(duì)于Django應(yīng)用程序中的每個(gè)model都會(huì)至少存在一個(gè)Manager

詳細(xì):https://docs.djangoproject.com/en/dev/topics/db/managers/

django實(shí)現(xiàn)軟刪除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="公司名稱")

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論