首页 > 解决方案 > Django Soft 删除和通用关系管理器

问题描述

我在一个项目中使用 Django 2.0,我正在实现一个软删除功能,这样我就可以恢复已删除的对象。
我在我的 Django 项目中使用了这个 软删除的实现,它工作得很好。但是某些模型具有与可能被软删除的对象的 GenericRelation。有没有办法实现像 BaseModelManager 这样的 GenericRelationManager,它会忽略软删除的对象?
例如,假设我有以下代码(从这个站点借来的):

from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType

class Activity(BaseModel):
    FAVORITE = 'F'
    LIKE = 'L'
    UP_VOTE = 'U'
    DOWN_VOTE = 'D'
    ACTIVITY_TYPES = (
        (FAVORITE, 'Favorite'),
        (LIKE, 'Like'),
        (UP_VOTE, 'Up Vote'),
        (DOWN_VOTE, 'Down Vote'),
    )


    user = models.ForeignKey(User)
    activity_type = models.CharField(max_length=1, choices=ACTIVITY_TYPES)
    date = models.DateTimeField(auto_now_add=True)

    # Below the mandatory fields for generic relation
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey()

from django.db import models
from django.contrib.contenttypes.fields import GenericRelation

from activities.models import Activity


class Post(models.Model):
    ...
    likes = GenericRelation(Activity)

class Question(models.Model):
    ...
    activities = GenericRelation(Activity)

class Answer(models.Model):
    ...
    votes = GenericRelation(Activity)

class Comment(models.Model):
    ...
    likes = GenericRelation(Activity)

如果我软删除一个活动,我仍然可以通过这些 GenericRelations 找到软删除的活动。我可以实现 GenericRelation 的行为,就像 BaseModelManager 一样,忽略软删除的活动?

标签: pythondjango

解决方案


推荐阅读