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. Model inheritance with content type by crucialfelix 5 years, 7 months ago
  2. DRY with common model fields (another way) by jmrbcu 6 years, 9 months ago
  3. Validating Model subclass by slacy 2 years, 3 months ago
  4. JSONable model base by girasquid 5 years, 2 months ago
  5. Automating URLs by jorjun 4 years, 10 months ago

Comments

(Forgotten your password?)