Django 和技术领域

Django and technical fields

我正在构建数据模型。我希望每个模型都有一些技术领域,例如:createdupdated。我不喜欢将这些字段添加到每个模型(你知道......干)。

我试图用createdupdated字段构建一个父class,并在其他模型中继承它,但是Django的ORM没有把created和模型 table 中的 updated 字段,而是为这两个字段创建另一个 table 并通过外键将其 link 到模型。那不是我想要的。

有没有可行的方法?

我做了很多次 :

class TimeStampedModel(models.Model):
    """
    An abstract base class model that provides self-
    updating 'created' and 'modified' fields
    """

    created = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)

    class Meta:
        abstract = True

其他型号:

from core.models import TimeStampedModel

class MyClass(TimeStampedModel):
    """
    CLASS LAMBDA
    """
    field = models.DecimalField(verbose_name=u"Name", max_digits=7, decimal_places=2)
    field2 = models.CharField(verbose_name=u"Name 2", max_length=200)

现在 ipython :

from bundle.models.my_class import MyClass
item = MyClass.objects.first()
print item.created 

现在当条目为 created (auto_now_add=True) 时设置 created 并且 modified 是当您.... modified 您的条目 ( auto_now=True).

神奇的是,它是一个抽象 class (doc here):

Abstract base classes are useful when you want to put some common information into a number of other models. You write your base class and put abstract=True in the Meta class. This model will then not be used to create any database table. Instead, when it is used as a base class for other models, its fields will be added to those of the child class.