0

I want to create two fields for creating an object in Django models. The first field is required and will use the built in DateTimeField.

Second field will take on the same data as in the first field, furthermore it should be possible to update the date without changing the data in the first field.

This is my class:

class MyClass(models.Model):
    ...
    created_at = models.DateTimeField(null=True)
    updated_at = models.DateTimeField(null=True)     # this field should take data 
    ... 

I looked for built-in Models which fulfill my requirements, but couldn't find the right one.

This class with auto_now_add won't show me any field.

class MyClass(models.Model):
    ...
    created_at = models.DateTimeField(**auto_now_add**=True)
    updated_at = models.DateTimeField(**auto_now**=True)    
    ... 
Yusuf Adel
  • 50
  • 5
atp55
  • 11
  • 3

1 Answers1

0

To autofill timestamps in a Django model, you can use the auto_now_add and auto_now options provided by Django's built-in DateTimeField or DateField fields. These options automatically set the field value to the current date and time when the object is created or updated, respectively.

Here's an example of how to use these options in a Django model:

from django.db import models

class MyModel(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

In the above example, created_at will be set to the current date and time when the object is first created and will not be modified afterwards. On the other hand, updated_at will be set to the current date and time every time the object is saved or updated.

Make sure to add the necessary import statements for models and define your own model fields as needed.

By using these options, you can eliminate the need to manually set timestamps in your Django model, as the framework will handle it automatically for you.