I want to deploy a way to active/inactive a model without delete it, like in User model that has a is_active field that we can deactivate a user, so I want to do same with whole model.
For example if I uncheck is_active in products model, this model will disappear! and all relation to products model was alternative with None.
CodePudding user response:
Perhaps you can create a BaseModel class that has an is_active property that all your other models inherit from.
Next you will want to override the delete
method on the BaseModel so that if delete is called, it inactivates it. You can also add a really_delete
function that calls the normal delete function if you really want to drop if from the DB.
class BaseModel(models.Model):
class Meta:
abstract = True
is_active = models.BooleanField(default=True)
def delete(self):
self.is_active = False
self.save()
def undelete(self):
self.is_active = True
self.save(request=request)
def really_delete(self):
super().delete()
CodePudding user response:
Add is_active field and override the delete method.
class Foo(models.Model):
is_active = models.BooleanField(verbose_name='is active?', default=True)
remove_datetime = models.DateTimeField(verbose_name='remove date', blank=True, null=True)
def delete(self, purge=False, using=None, keep_parents=False):
if purge:
return super(TrackedModel, self).delete(using, keep_parents)
else:
self.remove_datetime = timezone.now()
self.is_active = False
self.save()
For tacking a model carefully I use these models:
from django.db import models
from django.utils import timezone
class TimedModel(models.Model):
created = models.DateTimeField(default=timezone.now, verbose_name='created')
modified = models.DateTimeField(default=timezone.now, verbose_name="last modified")
def save(self, *args, **kwargs):
now = timezone.now()
if not self.id:
self.created = now
self.modified = now
return super(TimedModel, self).save(*args, **kwargs)
class Meta:
ordering = ('-created',)
abstract = True
class TrackedModel(TimedModel):
class Meta:
abstract = True
is_active = models.BooleanField(verbose_name='is active?', default=True)
remove_datetime = models.DateTimeField(verbose_name='remove date', blank=True, null=True)
def delete(self, purge=False, using=None, keep_parents=False):
if purge:
return super(TrackedModel, self).delete(using, keep_parents)
else:
self.remove_datetime = timezone.now()
self.is_active = False
self.save()