标签:efi sof *args 模型 models 保存 datetime filter add
is_delete=True
表示删除。为了查询方便,我们需要重新定义models中的Manager
。from django.db import models
from django.db.models.query import QuerySet
class SoftDeletableQuerySet(QuerySet):
def delete(self):
self.update(is_deleted=True)
class SoftDeletableManager(models.Manager):
"""
仅返回未被删除的实例
"""
_queryset_class = SoftDeletableQuerySet
def get_queryset(self):
"""
在这里处理一下QuerySet, 然后返回没被标记位is_deleted的QuerySet
"""
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 SoftDeleteMode(models.Model):
create_time = models.DateTimeField(verbose_name=‘添加时间‘, auto_now_add=True)
update_time = models.DateTimeField(verbose_name=‘更新时间‘, auto_now=True)
"""
抽象类,添加is_deleted 字段
"""
is_deleted = models.BooleanField(default=False)
class Meta:
abstract = True
# 重新定义objects为我们自己的管理器,查询和添加操作时会判断该数据是否被删除
objects = SoftDeletableManager()
def delete(self, using=None, soft=True, *args, **kwargs):
"""
这里需要真删除的话soft=False即可
"""
if soft:
self.is_deleted = True
self.save(using=using)
else:
return super(SoftDeleteMode, self).delete(using=using, *args, **kwargs)
# 时间为微秒的转换
@property
def _create_time(self):
return self.create_time.strftime("%Y-%m-%d %H:%M:%S")
@property
def _update_time(self):
return self.update_time.strftime("%Y-%m-%d %H:%M:%S")
标签:efi sof *args 模型 models 保存 datetime filter add
原文地址:https://www.cnblogs.com/se7enjean/p/13186903.html