Base Class For My Entities
Here is the base class of my entities. This one supports deleting of record by marking instead of permanently deleting the record:
class BaseModel(models.Model):
"""
Base model for all entities
"""
date_created = models.DateTimeField(auto_now_add=True)
date_updated = models.DateTimeField(auto_now=True, auto_now_add=True)
def delete(self, permanent=False):
"""
Delete a model by flagging. An optional parameter 'permanent' can be passed to permanently delete it
"""
if BaseModel.__deletable_type(self.__class__) and not permanent:
self.deleted = 1
self.save()
else:
models.Model.delete(self)
@classmethod
def all(cls, include_deleted=False):
"""
Get all query object with deleted records filtered
"""
deleted_field = hasattr(cls, "deleted")
if BaseModel.__deletable_type(cls) and not include_deleted:
query = cls.objects.all()
return query.filter(deleted=False)
else:
return cls.objects.all()
@classmethod
def __deletable_type(cls, input_cls):
"""
Check if this class is deletable by flagging. The algorithm is slow so it needs some tweaking later
"""
for b in input_cls.__bases__:
if b.__name__ == 'BaseDeletableUserModel': return True
return False
class Meta:
abstract = True
class BaseDeletableModel(BaseModel):
"""
A deletable base model
"""
deleted = models.BooleanField(default=False)
class Meta:
abstract = True
The code above still needs to be improved so any kind of comments will be appreciated.























Comments (0)