Useful when you want to keep only one instance of a model to be the default one.
This is a decorative way of doing the same as in http://djangosnippets.org/snippets/1830/
Can this be made better as a class decorator (not having to declare explicitly the save method) ?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25  | from functools import wraps
def unique_boolean(field):
    def factory(func):
        @wraps(func)
        def decorator(self):
            if getattr(self, field):
                try:
                    tmp = self.__class__.objects.get(**{ field: True })
                    if self != tmp:
                        setattr(tmp, field, False)
                        tmp.save()
                except self.__class__.DoesNotExist:
                    pass
            return func(self)
        return decorator
    return factory
# Usage:
class MyDefaultUniqueModel(models.Model):
    default = models.BooleanField()
    @unique_boolean('default')
    def save(self):
        super(MyDefaultUniqueModel, self).save()
 | 
More like this
- Add Toggle Switch Widget to Django Forms by OgliariNatan 1 month, 4 weeks ago
 - get_object_or_none by azwdevops 5 months, 2 weeks ago
 - Mask sensitive data from logger by agusmakmun 7 months, 2 weeks ago
 - Template tag - list punctuation for a list of items by shapiromatron 1 year, 9 months ago
 - JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 1 year, 9 months ago
 
Comments
Please login first before commenting.