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
@iljabauer
Copy link

Setter is not called by admin

@hugotox
Copy link

hugotox commented Apr 14, 2015

It doesn't work for queryset methods like Person.objects.filter(first_name='Joe')

@stephanschielke
Copy link

+1 @iljabauer
Same here.

@luizs81
Copy link

luizs81 commented Nov 28, 2016

It might work in plain Python classes, but it's ignored by Django.

@idrummer83
Copy link

so, how to realise such method???

@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