Login

DRY with common model fields

Author:
miracle2k
Posted:
July 14, 2007
Language:
Python
Version:
.96
Score:
5 (after 5 ratings)

If you have many models that all share the same fields, this might be an option. Please note that order matters: Your model need to inherit from TimestampedModelBase first, and models.Model second. The fields are added directly to each model, e.g. while they will be duplicated on the database level, you only have to define them once in your python code.

Not sure if there is a way to automate the call to TimestampedModelInit().

Tested with trunk rev. 5699. There is probably a slight chance that future revisions might break this.

 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. Template tag - list punctuation for a list of items by shapiromatron 2 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 1 week ago
  5. Help text hyperlinks by sa2812 11 months ago

Comments

Please login first before commenting.