Automatic creation date for Django model form objects?

前端 未结 2 1799
囚心锁ツ
囚心锁ツ 2020-12-12 10:00

What\'s the best way to set a creation date for an object automatically, and also a field that will record when the object was last updated?

models.py:

2条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-12 10:11

    Well, the above answer is correct, auto_now_add and auto_now would do it, but it would be better to make an abstract class and use it in any model where you require created_at and updated_at fields.

    class TimeStampMixin(models.Model):
        created_at = models.DateTimeField(auto_now_add=True)
        updated_at = models.DateTimeField(auto_now=True)
    
        class Meta:
            abstract = True
    

    Now anywhere you want to use it you can do a simple inherit and you can use timestamp in any model you make like.

    class Posts(TimeStampMixin):
        name = models.CharField(max_length=50)
        ...
        ...
    

    In this way, you can leverage object-oriented reusability, in Django DRY(don't repeat yourself)

提交回复
热议问题