Created
November 24, 2015 17:24
-
-
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!
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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__**! | |
""" | |
@daniel-jacob-pearson - we miss you and your code reviews.
come back!
buenas tardes, como usar el getattr?
good day, how to use getattr?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Would
hasattr(self, attrname)
work as well asattrname in self.__dict__
? Looking at__dict__
directly is more likely to conflict with someone else's super-nifty metaprogramming magic.