django / django/new-features

Immutable model objects

Open
#153 4 comments 4 reactions 0 assignees View on GitHub
Dominant language
No language data
Stars
188
Forks
7
PR merge metrics
No merged PRs in 30d

Description

### Code of Conduct

- [x] I agree to follow Django's Code of Conduct

### Feature Description

Provide a function or method that takes an existing Model instance and returns an immutable version of it.
```
obj = Model.objects.get(...)
immutable = obj.immutable()
```

Attempting to modify an immutable model object would raise an error, e.g.
```
immutable.field = ...

TypeError: Immutable object cannot be modified
```

### Problem

When retrieving a model object from a local in-process cache, ideally you don't want the calling logic to be able to mutate the object and potentially pollute it for a subsequent caller. Having an immutable object is an effective way of preventing weird bugs when code is using caching.

### Request or proposal

request

### Additional Details

I'm aware that it's kinda impossible to truly make an object immutable in Python, but making it difficult to mutate is enough to catch errors when using cached objects.

### Implementation Suggestions

_No response_

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.