There are places in my code where I want to temporarily change some of the attributes on a model object without changing the data in the database. Obviously Django and Python make this very easy to do, I just need to set the attribute without calling save.
But I'd like to know if there's a common pattern for making the object immutable so I don't accidentally call save somewhere later down the line and screw up the data in my database. And maybe "immutable" isn't the right word here, it's more like disassociating the object with the model so data can't ever get back to the database.
My first idea was to just override the save method to do nothing, would this be enough?
All you have to do is sub-class from Freezer . After initialization of the Python, I “freeze” the object with my overriding of the __delattr__ and __setattr__ methods on the object. I set _frozen = True which indicates the instance is now “frozen”. objects become immutable.
Model Inheritance in Django works almost identically to the way normal class inheritance works in python. In this article we will revolve around how to create abstract base class in Django Models. Abstract Base Class are useful when you want to put some common information into a number of other models.
TimeStampedModel - An Abstract Base Class model that provides self-managed created and modified fields.
One of the most powerful features of Django is its Object-Relational Mapper (ORM), which enables you to interact with your database, like you would with SQL.
I know this question is pretty old, but is very much still relevant.
The best, if somewhat curt solution I've come up with to date looks like so;
class ModelName(models.Model):
# fields, etc...
def save(self, *args, **kwargs):
if self.pk:
raise ValidationError("you may not edit an existing %s" % self._meta.model_name)
super(ModelName, self).save(*args, **kwargs)
This way users are informed that the action they are performing is unsupported, rather than just silently failing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With