A bit cleaner syntax for method attribute assignment; used in models for 'short_description'.
>from mysite.polls.models import Poll
>poll = Poll.objects.get(pk=1)
>poll.was_published_today.short_description
>>>'Published today?'
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
- Template tag - list punctuation for a list of items by shapiromatron 11 months, 3 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 12 months ago
- Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
- Help text hyperlinks by sa2812 1 year, 8 months ago
Comments
Please login first before commenting.