查询所有对象,包括 SoftDeletableModel 的软删除对象
Querying all objects including soft deleted ones of a SoftDeletableModel
我正在尝试摆脱自制解决方案,转而使用更标准的解决方案。我以前的模式:
class MarkDeleteManager(models.Manager):
use_for_related_fields = True
def get_queryset(self):
if "instance" in self._hints:
return super(MarkDeleteManager, self).get_queryset()
return super(MarkDeleteManager, self).get_queryset().filter(deleted=False)
def all_with_deleted(self):
return super(MarkDeleteManager, self).get_queryset()
def deleted_set(self):
return super(MarkDeleteManager, self).get_queryset().filter(deleted=True)
def using(self, *args, **kwargs):
''' if a specific record was requested, return it even if it's deleted '''
return self.all_with_deleted().using(*args, **kwargs)
我想用 django-model-util 的 SoftDeletableModel
替换它,但我在 SoftDeletableManagerMixin
中没有看到任何类似 all_with_deleted
的功能 - 它只会覆盖 get_queryset
就是这样。我的架构是去中心化的,当我通知其他节点软删除时,我需要访问这些节点。
所以我会这样解决:
from model_utils.models import SoftDeletableModel
class MyModel(SoftDeletableModel):
all_objects = models.Manager() # To access soft deleted objects as well
name = models.CharField()
...
这样我就可以通过说 MyModel.all_objects.all()
而不是旧模式的 MyModel.objects.all_with_deleted().all()
来访问所有对象。 MyModel.objects.all()
在这两种情况下都将只提供非软删除的。
我正在尝试摆脱自制解决方案,转而使用更标准的解决方案。我以前的模式:
class MarkDeleteManager(models.Manager):
use_for_related_fields = True
def get_queryset(self):
if "instance" in self._hints:
return super(MarkDeleteManager, self).get_queryset()
return super(MarkDeleteManager, self).get_queryset().filter(deleted=False)
def all_with_deleted(self):
return super(MarkDeleteManager, self).get_queryset()
def deleted_set(self):
return super(MarkDeleteManager, self).get_queryset().filter(deleted=True)
def using(self, *args, **kwargs):
''' if a specific record was requested, return it even if it's deleted '''
return self.all_with_deleted().using(*args, **kwargs)
我想用 django-model-util 的 SoftDeletableModel
替换它,但我在 SoftDeletableManagerMixin
中没有看到任何类似 all_with_deleted
的功能 - 它只会覆盖 get_queryset
就是这样。我的架构是去中心化的,当我通知其他节点软删除时,我需要访问这些节点。
所以我会这样解决:
from model_utils.models import SoftDeletableModel
class MyModel(SoftDeletableModel):
all_objects = models.Manager() # To access soft deleted objects as well
name = models.CharField()
...
这样我就可以通过说 MyModel.all_objects.all()
而不是旧模式的 MyModel.objects.all_with_deleted().all()
来访问所有对象。 MyModel.objects.all()
在这两种情况下都将只提供非软删除的。