decorator for method attribute assignment

 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
from django.db import models
from datetime import date

#function-type decorator
def addAttribute(attr, value):
    def wrap(meth):
        def wrapped(*args):
            return meth(*args)
        setattr(wrapped, attr, value)
        return wrapped
    return wrap

#class-type decorator
class set_attribute(object):
    def __init__(self, name, value):
        self.name = name 
        self.value = value
    
    def __call__(self, func):
        def wrapped(*args):
            return func(*args)
        setattr(wrapped, self.name, self.value)
        return wrapped

#USAGE
class Poll(models.Model):
    question = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')
    
    @set_attribute('short_description', 'Published today?')
    def was_published_today(self):
        return self.pub_date.date() == date.today()

More like this

  1. Finding related objects for instances in a queryset by akaihola 2 years, 2 months ago
  2. DRY custom ModelAdmin.list_display methods with a decorator by exogen 4 years, 8 months ago
  3. A ModelChoiceField with support for title in options based on a field in the model by celopes 2 years, 9 months ago
  4. PatchModelForm - A ModelForm subclass with the semantics of the PATCH HTTP method by gnrfan 11 months, 4 weeks ago
  5. PK->objects in view signature by AdamKG 5 years, 1 month ago

Comments

(Forgotten your password?)