I wanted to make the objects of a particular model approvable and store the timestamp of when that happened. In other frameworks/languages, I used to combined those in one "approved_at" field, which would be NULL if an object was currently unapproved.
I tried different approaches to implement this in django, and this is the best I came up with so far. Basically, the code in setattr makes sure that the field, once set, will not be updated again.
Overriding setattr__() could also be a solution to determining if a field value has changed in save(), a question that seems come up from time to time in #django.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
class ApprovedStateField(forms.fields.Field): widget = forms.CheckboxInput def clean(self, value): super(ApprovedStateField, self).clean(value) if bool(value): return datetime.datetime.now() else: return None class Keyword(models.Model): name = models.CharField(maxlength=30) approved_at = ApprovedStateField() def __setattr__(self, name, value): # don't change the approved_at attribute if it is already set if (name <> "approved_at") or (not hasattr(self, 'approved_at')) or (self.approved_at is None): super(Keyword, self).__setattr__(name, value)
More like this
- Serializer factory with Django Rest Framework by julio 5 months, 3 weeks ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 6 months, 1 week ago
- Help text hyperlinks by sa2812 7 months ago
- Stuff by NixonDash 9 months, 1 week ago
- Add custom fields to the built-in Group model by jmoppel 11 months, 2 weeks ago