TaeHwan. Park
TaeHwan. Park

Reputation: 23

how to dry code? (for python 3.6 django 1.10.5)

I do not know how to remove the overlap in the class. And what if we want to change the datetime format?

from django.db import models


class A(models.Model):
 created_time = models.DateTimeField(auto_now_add=True)
 updated_time = models.DateTimeField(auto_now=True)
class B(models.Model):
 created_time = models.DateTimeField(auto_now_add=True)
 updated_time = models.DateTimeField(auto_now=True)
class C(models.Model):
 created_time = models.DateTimeField(auto_now_add=True)
 updated_time = models.DateTimeField(auto_now=True)

Upvotes: 1

Views: 126

Answers (2)

Dmitrij
Dmitrij

Reputation: 116

and don't forget to use abstract = True

class BaseModel(models.Model): ... class Meta: abstract = True

or you will finish with 4 tables in your database including 'appname_basemodel' table

django doc model inheritance

Upvotes: 1

elethan
elethan

Reputation: 17003

Inheritance to the rescue:

class BaseModel(models.Model):
    created_time = models.DateTimeField(auto_now_add=True)
    updated_time = models.DateTimeField(auto_now=True)

class A(BaseModel):
    pass

class B(BaseModel):
    pass

class C(BaseModel):
    pass

Now A, B and C all have created_time and updated_time.

As for the second question about datetime format, you will not worry about that part in your models. The objects returned by created_time on an instance of A for example, will be a Python datetime object which can be formatted with strftime in your views (here is a good cheatsheet for the format codes), or with the date template tag in your templates.

Upvotes: 2

Related Questions