DRY with common model fields

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class TimestampedModelBase():
   
    def save(self): 
        if not self.id:
            self.created_at = datetime.datetime.today() 
        self.updated_at = datetime.datetime.today()
        models.Model.save(self)

def TimestampedModelInit(model_classes):
        for model_class in model_classes:
            if issubclass(model_class, TimestampedModelBase):
                model_class.add_to_class('created_at', models.DateTimeField(editable=False))
                model_class.add_to_class('updated_at', models.DateTimeField(editable=False))
                model_class.add_to_class('created_by', models.ForeignKey(User))

""" Use: """

class Company(TimestampedModelBase, models.Model):    
    name = models.CharField(maxlength=60)

TimestampedModelInit([Company])

Comments

pootytang (on September 27, 2007):

This is a very nice approach. Something to keep in mind though for the timestamps is you can use auto_now and auto_now_add arguments described in the django docs.

#

srid (on January 9, 2008):

You might want consider this script, http://www.djangosnippets.org/snippets/529/

#

(Forgotten your password?)

You may use Markdown syntax here, but raw HTML will be removed.