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
- Template tag - list punctuation for a list of items by shapiromatron 11 months, 1 week ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 2 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
Please login first before commenting.