1. 程式人生 > >django之軟刪除model

django之軟刪除model

軟刪除

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

預備知識

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,繼承SoftDeletableModel抽象基類

class CustomerInfo(SoftDeletableModel):  
     company =models.CharField(max_length=64,verbose_name="公司名稱")