使用“删除标记”进行删除和自动级联
由于我从来不想实际删除我的 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我想我已经找到了我一直在寻找的答案,因为显然描述我的用例的实际术语是 软删除级联在 软删除实现。
我会看看;还是谢谢你的回复。 :)
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. :)