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 custom fields to the built-in Group model by jmoppel 1 month, 2 weeks ago
- Month / Year SelectDateWidget based on django SelectDateWidget by pierreben 5 months ago
- Python Django CRUD Example Tutorial by tuts_station 5 months, 2 weeks ago
- Browser-native date input field by kytta 7 months ago
- Generate and render HTML Table by LLyaudet 7 months, 1 week ago
Comments
Please login first before commenting.