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 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | from functools import wraps
def unique_boolean(field, subset=[]):
"""
Allows to specify a unique boolean for a model.
"""
def cls_factory(cls):
def factory(func):
@wraps(func)
def decorator(self):
kwargs = { field: True }
for arg in subset:
if getattr(self, arg):
kwargs[arg] = getattr(self, arg)
if getattr(self, field):
try:
tmp = self.__class__.objects.get(**kwargs)
if self != tmp:
setattr(tmp, field, False)
tmp.save()
except self.__class__.DoesNotExist:
if getattr(self, field) != True:
setattr(self, field, True)
else:
if self.__class__.objects.filter(**kwargs).count() == 0:
setattr(self, field, True)
return func(self)
return decorator
if hasattr(cls, 'save'):
cls.save = factory(cls.save)
return cls
return cls_factory
# Example: keep the 'main' field unique for the phones of each user
@unique_boolean('main', subset=['user'])
class Phone(models.Model):
user = models.ForeignKey(User)
main = models.BooleanField()
|
More like this
- True Unique Boolean Decorator by kunitoki 1 year, 4 months ago
- TrueNoneField by diverman 3 years, 6 months ago
- RequiredNullBooleanField by wwu.housing 4 years, 2 months ago
- Fix for the bad behaviour of GenericForeignKey field by pinkeen 2 years, 5 months ago
- DRY with common model fields (another way) by jmrbcu 5 years, 11 months ago
Comments