It is common to include timestamps in your models for the creation and modification of your model instances. In this recipe, you will learn how to create a simple model mixin that saves the creation and modification dates and times for your model. Using such a mixin will ensure that all of the models use the same field names for the timestamps, and have the same behaviors.
Creating a model mixin to handle creation and modification dates
Getting ready
If you haven't yet done so, create the myproject.apps.core package to save your mixins. Then, create the models.py file in the core package.
How to do it...
Open the models.py file in your myprojects.apps.core package, and insert the following content there:
# myproject/apps/core/models.py
from django.db import models
from django.utils.translation import gettext_lazy as _
class CreationModificationDateBase(models.Model):
"""
Abstract base class with a creation and modification date and time
"""
created = models.DateTimeField(
_("Creation Date and Time"),
auto_now_add=True,
)
modified = models.DateTimeField(
_("Modification Date and Time"),
auto_now=True,
)
class Meta:
abstract = True
How it works...
The CreationModificationDateMixin class is an abstract model, which means that extending model classes will create all of the fields in the same database table—that is, there will be no one-to-one relationships that make the table more complex to handle.
This mixin has two date-time fields, created and modified. With the auto_now_add and auto_now attributes, the timestamps will be saved automatically when saving a model instance. The fields will automatically get the editable=False attribute, and thus will be hidden in administration forms. If USE_TZ is set to True in the settings (which is the default and recommended), time-zone-aware timestamps will be used. Otherwise, time-zone-naive timestamps will be used. Timezone-aware timestamps are saved in the Coordinated Universal Time (UTC) time zone in the database and converted to the default time zone of the project when reading or writing them. Time-zone-naive timestamps are saved in the local time zone of the project in the database; they are not practical to use in general, because they make time management between time zones more complicated.
To make use of this mixin, we just have to import it and extend our model, as follows:
# myproject/apps/ideas/models.py
from django.db import models
from myproject.apps.core.models import CreationModificationDateBase
class Idea(CreationModificationDateBase):
# other fields, attributes, properties, and methods…
See also
- The Using model mixins recipe
- The Creating a model mixin to take care of meta tags recipe
- The Creating a model mixin to handle generic relations recipe