软删除
简单的说,就是当执行删除操作的时候,不正真执行删除操作,而是在逻辑上删除一条记录。这样做的好处是可以统计数据,可以进行恢复操作等等。
预备知识
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="公司名称")
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件!
如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
白云城资源网 Copyright www.dyhadc.com
暂无“django之自定义软删除Model的方法”评论...
更新日志
2025年01月10日
2025年01月10日
- 小骆驼-《草原狼2(蓝光CD)》[原抓WAV+CUE]
- 群星《欢迎来到我身边 电影原声专辑》[320K/MP3][105.02MB]
- 群星《欢迎来到我身边 电影原声专辑》[FLAC/分轨][480.9MB]
- 雷婷《梦里蓝天HQⅡ》 2023头版限量编号低速原抓[WAV+CUE][463M]
- 群星《2024好听新歌42》AI调整音效【WAV分轨】
- 王思雨-《思念陪着鸿雁飞》WAV
- 王思雨《喜马拉雅HQ》头版限量编号[WAV+CUE]
- 李健《无时无刻》[WAV+CUE][590M]
- 陈奕迅《酝酿》[WAV分轨][502M]
- 卓依婷《化蝶》2CD[WAV+CUE][1.1G]
- 群星《吉他王(黑胶CD)》[WAV+CUE]
- 齐秦《穿乐(穿越)》[WAV+CUE]
- 发烧珍品《数位CD音响测试-动向效果(九)》【WAV+CUE】
- 邝美云《邝美云精装歌集》[DSF][1.6G]
- 吕方《爱一回伤一回》[WAV+CUE][454M]