python - 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 一样,忽略软删除的活动?
解决方案
推荐阅读
- c - 实现 linux shell 时的 emacs
- symfony - 在“App\Entity\Slider#user”中找不到目标实体用户
- python - 有效地确定应该属于哪个方格观测值
- c - 为什么它在 3GB 地址空间之外显示帧指针?
- regex - 如何使用perl将n个数字添加到字符串中
- java - NullPointerException:尝试在空对象引用上调用虚拟方法“void android.widget.ImageView.setImageResource(int)”
- angular - 以 Angular 形式获取自动填充的值不起作用
- reactjs - 如何将 React 应用程序迁移到 React Router 以便从路径中检索参数
- python - 向量化嵌套 for 循环
- swift - 为短片、高分辨率视频添加观察者