使用“删除标记”进行删除和自动级联

发布于 2024-12-11 15:39:00 字数 936 浏览 1 评论 0原文

由于我从来不想实际删除我的 USER (BASE) 对象,因此我在我的 BASE 模型上引入了一个 delete_date

class BASE (models.Model):

    class Meta:

        abstract = True
        app_label = 'base'
        verbose_name_plural = 'bases'

    objects = BASE_MANAGER ()

    insert_date = models.DateTimeField (default = datetime.now (), auto_now_add = True)
    update_date = models.DateTimeField (default = datetime.now (), auto_now = True)
    delete_date = models.DateTimeField (null = True, blank = True)

    def save (self):

        super (BASE, self).save ()

    def delete (self):

        if not self.delete_date:
            self.update_date = datetime.now ()
            self.delete_date = datetime.now ()
            self.save ()
        else:
            pass ## no delete!

现在,因为我'没有在BASE.delete中包含super(BASE, self).delete(),没有执行实际的SQL,这很好;不幸的是,这也阻止了外键的级联。 Django 有没有一种优雅的方法来实现这一点?

Since I never want to actually delete my USER (BASE) objects, I've introduced a delete_date on my BASE model:

class BASE (models.Model):

    class Meta:

        abstract = True
        app_label = 'base'
        verbose_name_plural = 'bases'

    objects = BASE_MANAGER ()

    insert_date = models.DateTimeField (default = datetime.now (), auto_now_add = True)
    update_date = models.DateTimeField (default = datetime.now (), auto_now = True)
    delete_date = models.DateTimeField (null = True, blank = True)

    def save (self):

        super (BASE, self).save ()

    def delete (self):

        if not self.delete_date:
            self.update_date = datetime.now ()
            self.delete_date = datetime.now ()
            self.save ()
        else:
            pass ## no delete!

Now since I've not included super (BASE, self).delete () in BASE.delete no actual SQL is performed, which is fine; unfortunately this also stops the cascading for foreign keys. Is there an elegant way to achieve this in Django?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

拥抱影子 2024-12-18 15:39:00

我想我已经找到了我一直在寻找的答案,因为显然描述我的用例的实际术语是 软删除级联软删除实现

我会看看;还是谢谢你的回复。 :)

I think I've found the answer I've been looking for, since apparently the actual term that describes my use case is "soft delete" described in soft delete cascading implemented at soft delete implementation.

I'll have a look at that; still thank you for the responses. :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文