查询所有对象,包括软删除的SoftDeletableModel

时间:2018-03-08 16:15:35

标签: django python-2.7 soft-delete django-model-utils

我试图摆脱家酿解决方案,以支持更标准的解决方案。我之前的模式:

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替换它,但我在all_with_deleted中看不到任何SoftDeletableManagerMixin类似的功能 - 它只会覆盖get_queryset而且会覆盖它。我的架构是分散的,当我通知其他节点软删除时,我需要访问它们。

1 个答案:

答案 0 :(得分:0)

所以我会这样解决:

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()将仅提供非软删除的内容。