Django实现软删除

from django.db import models
from django.contrib.auth.models import AbstractUser
from django.db.models import QuerySet


class MySoftDeletableQuerySet(QuerySet):
    def delete(self):
        self.update(is_delete=True)


class BaseManager(models.Manager):
    _queryset_class = MySoftDeletableQuerySet

    def get_queryset(self):
        return super().get_queryset().filter(is_delete=False)


class BaseModel(models.Model):
    create_time = models.DateField(auto_now_add=True, verbose_name='创建时间')
    update_time = models.DateField(auto_now=True, verbose_name='修改时间')
    is_delete = models.BooleanField(default=False, verbose_name='是否删除')

    def delete(self, using=None, keep_parents=False):
        self.is_delete = True
        self.save()

    objects = BaseManager()

    class Meta:
        abstract = True  # 抽象基类

你可能感兴趣的:(Django实现软删除)