Django 2 DateTimeField format manual assignment in the program

Requirement description

Generally, when setting the creation time and update time in the data model, the format of DateTimeField will be used, and the automatic setting of time will also be set. An example is as follows:

create_time = models.DateTimeField(auto_now_add=True, verbose_name='Creation time')
update_time = models.DateTimeField(auto_now=True, verbose_name='Update time')

You can see that auto is used above_ now_ Add and auto_now as the automatic setting time.

  • DateTimeField.auto_now

 the default value of this parameter is false. When it is set to true, the value of this field can be set to the current time when saving, and will be automatically updated every time the model is modified. Therefore, this parameter is very convenient when the "last modification time" needs to be stored. It should be noted that when this parameter is set to true, it does not simply mean that the default value of the field is the current time, but that the field will be "forced" to be updated to the current time, and you cannot assign a value to the field manually in the program; If you use the admin manager with django, this field is read-only in admin. "

  • DateTimeField.auto_now_add

The default value of this parameter is also False. When it is set to True, the field value will be set to the time when the model object is created for the first time. When the object is modified later, the field value will not be updated. This attribute is usually used in scenarios where the creation time is stored. And auto_now is similar to auto_now_add is also mandatory. Once it is set to True, the field cannot be assigned manually in the program, and the field will become read-only in admin. "

From the above description, if these two parameters are set, the values cannot be modified manually. So, if I want to set a DateTimeField field that can be assigned manually, how should I set it and assign it?

Method of assignment

In fact, the DateTimeField field corresponds to datetime in Python Datetime, you can also use Django utils. timezone. Now() to set the time.

# Import datetime
In [10]: import datetime

# Print the current time format of datetime
In [11]: datetime.datetime.now()
Out[11]: datetime.datetime(2019, 9, 19, 10, 40, 23, 944737)

# Import Django utils. timezone
In [12]: from django.utils import timezone

# Print current time format
In [13]: timezone.now()
Out[13]: datetime.datetime(2019, 9, 19, 10, 42, 33, 721221)

In [14]: datetime.datetime.now()
Out[14]: datetime.datetime(2019, 9, 19, 10, 42, 53, 180852)

In [15]:

As you can see, each printed time format is consistent. Let's write an example to assign a custom time field with these two methods.

Example

Set two time fields

task_startup_time = models.DateTimeField(blank=True, null=True, default=None, verbose_name='Task start execution time')
task_expected_end_time = models.DateTimeField(blank=True, null=True, default=None, verbose_name='Expected end time of task')

The complete model classes are as follows:

class TaskScenario(BaseModel):
    """Task scenario"""
    users = models.IntegerField(verbose_name='Number of concurrent users')
    rate = models.IntegerField(verbose_name='Number of users started per second')
    task_startup_time = models.DateTimeField(blank=True, null=True, default=None, verbose_name='Task start execution time')
    task_expected_end_time = models.DateTimeField(blank=True, null=True, default=None, verbose_name='Expected end time of task')
    create_user = models.ForeignKey('user.User', blank=True, null=True, default=None,verbose_name='Create user',on_delete=models.SET_NULL) # Create user

    class Meta:
        db_table = 'pf_task_scenario'
        verbose_name = 'Task scenario'
        verbose_name_plural = verbose_name
        ordering = ['id'] # sort field

Execution setup time

In [1]: from tasks_manager.models import TaskScenario

In [4]: task_scenario = TaskScenario.objects.get(id=41)

In [5]: task_scenario.task_startup_time

In [6]: task_scenario.task_expected_end_time

In [10]: import datetime

In [11]: datetime.datetime.now()
Out[11]: datetime.datetime(2019, 9, 19, 10, 40, 23, 944737)

In [12]: from django.utils import timezone

In [13]: timezone.now()
Out[13]: datetime.datetime(2019, 9, 19, 10, 42, 33, 721221)

In [15]: task_scenario.task_startup_time = datetime.datetime.now()

In [16]: task_scenario.task_expected_end_time = timezone.now()

In [17]: task_scenario.save()

In [18]: task_scenario.task_startup_time
Out[18]: datetime.datetime(2019, 9, 19, 11, 7, 13, 499454)

In [19]: task_scenario.task_expected_end_time
Out[19]: datetime.datetime(2019, 9, 19, 11, 7, 33, 471270)

Query the saved time data in mysql as follows:

mysql> select * from pf_task_scenario where id = 41 \G
*************************** 1. row ***************************
                    id: 41
           create_time: 2019-09-09 14:44:25.668503
           update_time: 2019-09-19 11:07:38.133910
             is_delete: 0
                 users: 1000
                  rate: 100
        create_user_id: 5
task_expected_end_time: 2019-09-19 11:07:33.471270 # Use datetime datetime. Now (), you can see that the data of the two time parameters are basically the same
     task_startup_time: 2019-09-19 11:07:13.499454 # Use timezone Now () can see that the data of the two time parameters are basically the same
1 row in set (0.00 sec)

mysql>

Added by Shagrath on Wed, 19 Jan 2022 14:50:20 +0200