Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I make a django model object immutable?

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?

like image 209
guidoism Avatar asked Mar 08 '11 18:03

guidoism


People also ask

How do you make an object immutable in Python?

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.

Can we inherit models in Django?

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.

What is timestamped model in Django?

TimeStampedModel - An Abstract Base Class model that provides self-managed created and modified fields.

Is Django model ORM?

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.


1 Answers

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.

like image 123
pnovotnak Avatar answered Oct 04 '22 18:10

pnovotnak