Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save igniteflow/5539439 to your computer and use it in GitHub Desktop.
Save igniteflow/5539439 to your computer and use it in GitHub Desktop.
Custom getter and setter for Django model fields. This allows custom logic to be added to getters and setters without making any changes to existing code or database schema.
from django.db import models
class Person(models.Model):
_first_name = models.CharField(max_length=30, db_column='first_name')
last_name = models.CharField(max_length=30)
@property
def first_name(self):
"""your logic here, return value"""
return "foo"
@first_name.setter
def first_name(self, value):
self._first_name = value
@andrelcunha
Copy link

Worked like a charm. Thanks

@mmkhitaryan
Copy link

When are the setters called? Do they get called on every model change operation for the field, or only when I do .create?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment