📜  django datetimefield default - Python (1)

📅  最后修改于: 2023-12-03 15:00:26.352000             🧑  作者: Mango

Django DateTimeField Default

When using Django's DateTimeField in a model, you can set a default value for it. This default value will be used if no value for the field is provided when the object is created.

Setting a default value

To set a default value for a DateTimeField, simply add the default parameter to the field definition, and specify the default value as a datetime.datetime, datetime.date, or a string in ISO 8601 format.

from django.db import models
from datetime import datetime

class MyModel(models.Model):
    created_at = models.DateTimeField(default=datetime.now)

In the above example, the created_at field will default to the current date and time.

Common default values

There are a few common default values that you can use for DateTimeField:

  • datetime.now - Current date and time.
  • datetime.utcnow - Current UTC date and time.
  • timezone.now - Current date and time in the project's default timezone (requires django.utils.timezone).

You can use these default values by importing them from the datetime or django.utils.timezone module.

Custom default values

If you need a custom default value for your DateTimeField, you can use a function that returns a datetime object.

from datetime import datetime, timedelta

def default_end_time():
    return datetime.now() + timedelta(days=7)

class MyModel(models.Model):
    end_time = models.DateTimeField(default=default_end_time)

In the above example, the end_time field will default to the current date and time plus 7 days.

Conclusion

Setting a default value for a DateTimeField is very easy in Django. You can use one of the common default values, or create a custom default value using a function.

Remember that the default value will only be used if no value for the field is provided when the object is created.