In django do models have a default timestamp field?

前端 未结 6 1324
误落风尘
误落风尘 2021-01-30 09:53

In django - is there a default timestamp field for all objects? That is, do I have to explicitly declare a \'timestamp\' field for \'created on\' in my Model - or is there a way

相关标签:
6条回答
  • 2021-01-30 10:23

    No such thing by default, but adding one is super-easy. Just use the auto_now_add parameter in the DateTimeField class:

    created = models.DateTimeField(auto_now_add=True)
    

    You can also use auto_now for an 'updated on' field. Check the behavior of auto_now here.

    For auto_now_add here.

    A model with both fields will look like this:

    class MyModel(models.Model):
        created_at = models.DateTimeField(auto_now_add=True)
        updated_at = models.DateTimeField(auto_now=True)
    
    0 讨论(0)
  • 2021-01-30 10:31

    Automagically doesn't sound like something django would do by default. It wouldn't force you to require a timestamp.

    I'd build an abstract base class and inherit all models from it if you don't want to forget about the timestamp / fieldname, etc.

    class TimeStampedModel(models.Model):
         created_on = models.DateTimeField(auto_now_add=True)
    
         class Meta:
             abstract = True
    

    It doesn't seem like much to import wherever.TimeStampedModel instead of django.db.models.Model

    class MyFutureModels(TimeStampedModel):
        ....
    
    0 讨论(0)
  • 2021-01-30 10:32

    I think i would go with

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

    I need some clarifications on using

    class TimeStampedModel(models.Model):
        created_on = models.DateTimeField(auto_now_add=True)
    
        class Meta:
             abstract = True
    
    0 讨论(0)
  • 2021-01-30 10:38

    You can try django-extensions

    if you want to use time-stamp abstract model

    from django_extensions.db.models import TimeStampedModel
    
    class A(TimeStampedModel):
       ...
    

    It has other abstract models. you can use that too.

    0 讨论(0)
  • 2021-01-30 10:41

    If you want to be able to modify this field, set the following instead of auto_now_add=True:

    For Date

    from datetime import date
    
    models.DateField(default=date.today)
    

    For DateTime

    from django.utils import timezone
    
    models.DateTimeField(default=timezone.now)
    
    0 讨论(0)
  • 2021-01-30 10:48

    If you are using django-extensions (which is a good app for adding functionality to the django-admin.py command line helper) you can get these model fields for free by inheriting from their TimeStampedModel or using their custom TimeStamp fields

    0 讨论(0)
提交回复
热议问题