class Task(models.Model):
title = models.CharField(max_length=100)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
# Prasath creates a task:
task = Task.objects.create(title='Complete Django project')
print(f"Created: {task.created_at}")
print(f"Updated: {task.updated_at}")
# After 1 hour, Prasath updates the task:
task.title = 'Complete Django project - Updated'
task.save()
print(f"Created: {task.created_at}")
print(f"Updated: {task.updated_at}")Django Model Field: DateTimeField auto_now vs auto_now_add
Both created_at and updated_at will have the same value after the update because they are both set at creation time.
created_at remains unchanged (set only at creation), but updated_at is updated to the current time with each save() call.
Both fields will be updated to the current time because auto_now and auto_now_add both update on every save.
updated_at will remain unchanged because auto_now only works on the first save.
Show answer & explanationAnswer
Correct answer
created_at remains unchanged (set only at creation), but updated_at is updated to the current time with each save() call.
Explanation
auto_now_add sets the field only on creation, while auto_now updates the field every time the model is saved. Therefore, created_at remains unchanged but updated_at reflects the new save time.
All 30 Django Models and Database Design questions
- 1.What is the primary purpose of Django Models?
- 2.Which field type should be used to store an email address in a Django Model?
- 3.What does the Meta class inside a Django Model do?
- 4.Which relationship type is used when one model can have many instances of another model?
- 5.What is the purpose of the `__str__` method in a Django Model?
- 6.Which field attribute makes a field mandatory in Django Models?
- 7.What does the `on_delete` parameter do in a ForeignKey relationship?
- 8.Which of the following is a valid Django field type for storing boolean values?
- 9.What is the default behavior when you don't specify `null=True` for a field in Django?
- 10.Which method is used to retrieve a single object from the database in Django?
- 11.Understanding Django Model Meta Options
- 12.Scenario:
- 13.Django QuerySet Filter vs Get Method
- 14.Coding:
- 15.Scenario:
- 16.Understanding Django Model Inheritance
- 17.Coding:
- 18.Scenario:
- 19.Django Model Manager and QuerySet Methods
- 20.Coding:
- 21.Django Model Inheritance Strategy Selection
- 22.Django QuerySet Optimization with select_related vs prefetch_related
- 23.Django Model Field Choices and Validation
- 24.Django Model Relationships:
- 25.Django Model Signals and Database Consistency
- 26.Django Model Meta Options:
- 27.Django Model Managers and Custom QuerySets
- 28.Django Model Field:
- 29.Django Model Validation:
- 30.Django Model Aggregation and Annotation
