In Django, you can create a model with a DateTimeField that automatically sets the value to the current date and time when an object is created using the auto_now_add
parameter. Here's how you can do it:
pythonfrom django.db import models
class MyModel(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
In this example:
MyModel
is the name of your model class.created_at
is the field name, but you can name it whatever you like.models.DateTimeField
is used to define a field that stores date and time information.auto_now_add=True
is a parameter that automatically sets the field to the current date and time when an object is created.After defining your model, don't forget to run python manage.py makemigrations
and python manage.py migrate
to apply the changes to your database schema.