Skip to content

Instantly share code, notes, and snippets.

@thelonecabbage
Created November 24, 2015 17:24
Show Gist options
  • Save thelonecabbage/c77ca9262efc22e04085 to your computer and use it in GitHub Desktop.
Save thelonecabbage/c77ca9262efc22e04085 to your computer and use it in GitHub Desktop.
How to create a setter in djano models that doesn't mess up the admin or .filter queries!
class MyModel(models.Model):
foo = models.CharField(max_length=20)
bar = models.CharField(max_length=20)
def __setattr__(self, attrname, val):
setter_func = 'setter_' + attrname
if attrname in self.__dict__ and callable(getattr(self, setter_func, None)):
super(MyModel, self).__setattr__(attrname, getattr(self, setter_func)(val))
else:
super(MyModel, self).__setattr__(attrname, val)
def setter_foo(self, val):
return val.upper()
"""
Getters and setters are long missing from Django models.
The currently recommended method is to rename fileds with an underscore, and use @property to work as a setter and getter.
But he @property causes problems in admin, and .filter(_foo).
A better solution would be to override __setattr__ except that this can cause problems initializing the ORM object
from the DB. However, there is a trick to get around this, and it's universal.
The secret is '**attrname in self.__dict__**'. When the model initializes either from new or hydrated
from the **__dict__**!
"""
@cristianmoreno2017
Copy link

buenas tardes, como usar el getattr?

@cristianmoreno2017
Copy link

good day, how to use getattr?

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