Django 代码片段

Django 软删除方案

from django.db import models
from django.utils import timezone


class ExcludeDeletedManager(models.Manager):
    def get_queryset(self):
        return super().get_queryset().filter(deleted_at__isnull=True)

class IncludeDeletedManager(models.Manager):
    def get_queryset(self):
        return super().get_queryset()
  
class AbstractTimeModel(models.Model):
    created_at = models.DateTimeField("创建时间", auto_now_add=True, null=True)
    updated_at = models.DateTimeField("更新时间", auto_now=True, null=True)
    deleted_at = models.DateTimeField("删除时间", blank=True, null=True)
    objects = ExcludeDeletedManager()
    all_objects = IncludeDeletedManager()
    
    def delete(self, using=None, keep_parents=False):
        self.deleted_at = timezone.now()
        self.save()
		
    class Meta:
        abstract = True