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
- Browser-native date input field by kytta 1 month, 1 week ago
- Generate and render HTML Table by LLyaudet 1 month, 2 weeks ago
- My firs Snippets by GutemaG 1 month, 3 weeks ago
- FileField having auto upload_to path by junaidmgithub 2 months, 4 weeks ago
- LazyPrimaryKeyRelatedField by LLyaudet 3 months ago
Comments
Please login first before commenting.