如何在不使用抽象模型和管理器的情况下覆盖 Django DeleteView

发布于 2025-01-11 18:20:56 字数 1117 浏览 0 评论 0原文

我试图通过覆盖 DeleteView 中的删除方法来从数据库中软删除条目,但它不起作用。属性 active 应设置为 False。我无法使用抽象模型和管理器,因为我的父模型最初必须具有活动属性。 我的观点

class PersonDeleteView(DeleteView):
model = Person
template_name = 'contacts/deleteperson.html'
success_url = reverse_lazy('persons')

def delete(self, *args, **kwargs):
        self.object = self.get_object()
        self.object.active = False 
        return HttpResponseRedirect(self.get_success_url())

父模型

class AddressEntry(models.Model):

GENDER = (
    ('Male', 'Male'),
    ('Female', 'Female'),
)
gender = models.CharField( max_length= 20, choices=GENDER, default='Male')   
name = models.CharField(max_length=100)
firstname = models.CharField(max_length=100)
birthdate = models.DateField()
active = models.BooleanField(default=True)

def __str__(self):
    return self.name

def soft_delete(self):
    self.active = False
    self.save()

子模型

class Person(AddressEntry):
parentname = models.CharField(max_length=100)
job =  models.CharField(max_length=100)

I am trying to soft delete entry from my DB by overriding delete method in DeleteView but it is not working. Attribute active should be set to False. I can't use Abstract model and Manager because my parent model must originally have active attribute.
my view

class PersonDeleteView(DeleteView):
model = Person
template_name = 'contacts/deleteperson.html'
success_url = reverse_lazy('persons')

def delete(self, *args, **kwargs):
        self.object = self.get_object()
        self.object.active = False 
        return HttpResponseRedirect(self.get_success_url())

parent model

class AddressEntry(models.Model):

GENDER = (
    ('Male', 'Male'),
    ('Female', 'Female'),
)
gender = models.CharField( max_length= 20, choices=GENDER, default='Male')   
name = models.CharField(max_length=100)
firstname = models.CharField(max_length=100)
birthdate = models.DateField()
active = models.BooleanField(default=True)

def __str__(self):
    return self.name

def soft_delete(self):
    self.active = False
    self.save()

child model

class Person(AddressEntry):
parentname = models.CharField(max_length=100)
job =  models.CharField(max_length=100)

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

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

发布评论

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

评论(1

握住我的手 2025-01-18 18:20:57

修改后是否尝试保存实例?

def delete(self, *args, **kwargs):
        self.object = self.get_object()
        self.object.active = False
        self.object.save()
        return HttpResponseRedirect(self.get_success_url())

Did you try to save the instance after modifying it ?

def delete(self, *args, **kwargs):
        self.object = self.get_object()
        self.object.active = False
        self.object.save()
        return HttpResponseRedirect(self.get_success_url())
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文