Login

True Unique Boolean Decorator

Author:
kunitoki
Posted:
February 6, 2012
Language:
Python
Version:
1.3
Tags:
model unique boolean
Score:
2 (after 2 ratings)

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

  1. True Unique Boolean Model Decorator by kunitoki 3 years ago
  2. Unique naming for file uploads by mindcruzer 2 years, 8 months ago
  3. Add validation for 'unique' and 'unique_together' constraints to newforms created dynamically via form_for_model or form_for_instance by bikeshedder 7 years, 12 months ago
  4. decorator to add GUID Field to Django Models by trubliphone 2 years, 3 months ago
  5. Automate unique slug (again) by davidwtbuxton 7 years ago

Comments

Please login first before commenting.