我已经在我的项目中创建了软删除,并且工作正常。但是问题是我正在使用User
内置模型,并且将OneToOneField
与UserProfile
一起使用。现在soft_delete
函数在UserProfile
模型中,即时通讯使用generic.DeleteView
删除用户。问题是我无法将User
的对象传递给UserProfile
来将user_is_deleted
设置为True
。这是我的代码。
Views.py
class UserDeleteView(LoginRequiredMixin, generic.DeleteView):
model = User
template_name = 'users/user_confirm_delete.html'
success_url = '/users/'
def delete(self, request, *args, **kwargs):
self.object = self.get_object()
self.object.soft_delete()
return HttpResponseRedirect(self.get_success_url())
Models.py
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
user_company = models.ForeignKey(Company, on_delete=models.CASCADE)
user_role = models.ForeignKey(Roles, on_delete=models.CASCADE)
user_is_deleted = models.BooleanField(default=False)
user_deleted_at = models.DateTimeField(blank=True, null=True)
def soft_delete(self):
self.user_is_deleted = True
self.user_deleted_at = timezone.now() - tdelta(days=-1)
self.save()
答案 0 :(得分:2)
更改此
@classmethod
def soft_delete(self):
...
答案 1 :(得分:1)
将您的 delete()
方法更改为
def delete(self, request, *args, **kwargs):
self.object = self.get_object()
self.object.userprofile.soft_delete()
return HttpResponseRedirect(self.get_success_url())