91超碰碰碰碰久久久久久综合_超碰av人澡人澡人澡人澡人掠_国产黄大片在线观看画质优化_txt小说免费全本

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

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

發布時間:2020-09-03 20:31:16 來源:腳本之家 閱讀:455 作者:我愛學python 欄目:開發技術

軟刪除

簡單的說,就是當執行刪除操作的時候,不正真執行刪除操作,而是在邏輯上刪除一條記錄。這樣做的好處是可以統計數據,可以進行恢復操作等等。

預備知識

Managers

Managers 是django models 提供的一個用于提供數據庫查詢操作的接口,對于Django應用程序中的每個model都會至少存在一個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="公司名稱")

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

闸北区| 肇源县| 芮城县| 玛多县| 沐川县| 桑植县| 东安县| 龙泉市| 晋江市| 英超| 湘潭市| 余姚市| 洱源县| 永康市| 太白县| 信丰县| 宾阳县| 时尚| 新沂市| 鄯善县| 托克托县| 泸定县| 宽甸| 土默特右旗| 邛崃市| 柞水县| 洛南县| 博客| 宁陕县| 岫岩| 呼玛县| 加查县| 府谷县| 聂拉木县| 都安| 梨树县| 尉氏县| 华安县| 清镇市| 郑州市| 西乡县|