Automatic creation date for Django model form objects?

前端 未结 2 1798
囚心锁ツ
囚心锁ツ 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)

    0 讨论(0)
  • 2020-12-12 10:12

    You can use the auto_now and auto_now_add options for updated_at and created_at respectively.

    class MyModel(models.Model):
        created_at = models.DateTimeField(auto_now_add=True)
        updated_at = models.DateTimeField(auto_now=True)
    
    0 讨论(0)
提交回复
热议问题