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])

More like this

  1. DRY with common model fields (another way) by jmrbcu 5 years, 11 months ago
  2. SelfForeignKey to prevent hierarchical loops by jamesgpearce 3 years, 4 months ago
  3. "Approved" field with timestamp by miracle2k 5 years, 11 months ago
  4. Automating URLs by jorjun 3 years, 12 months ago
  5. {% renderonce %} template tag by corrr 3 years ago

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?)