Django base models
In the vast landscape of web application development, adhering to consistent coding patterns and standards plays a vital role in creating maintainable and reusable code.
When starting a new Django project, it's a good idea to define a set of base models that can be used as the foundation for all of your other models. This will help ensure that your models are consistent and predictable, and will make it easier to add new features in the future.
To do this, we can create a new abstract base model class that contains all of the common fields and behaviors that you want your models to have. Then, we can create subclasses of this base model class for each of your models.
Save creation and modification timestamps
Saving creation and modification timestamps is a common need in many web applications, to achieve this consistenly across all of our project models, we can create an abstract base model class that contains the created_at
and updated_at
fields, and then use this base model class as the foundation for all of our other models.
class TimestampedModel(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
abstract = True
Use UUIDs as primary keys instead of integers
Using integers as primary keys is a common practice in Django, but it's not the only option. In fact, there are several advantages to using UUIDs instead of integers.
With the following snippet, we can create a new abstract base model class that uses UUIDs as primary keys instead of integers:
class UUIDModel(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
class Meta:
abstract = True
Putting it all together
Now that we've defined our TimestampedModel
and UUIDModel
classes, we can use them individually in our project or combine them into a single abstract base model class that can be used as the foundation for all of our other models:
class BaseProjectModel(TimestampedModel, UUIDModel):
class Meta:
abstract = True
ordering = ['-created_at']
Using this approach, we can create a new model like this:
class Project(BaseProjectModel):
name = models.CharField(max_length=255)
description = models.TextField()
This will create a new Project
model that inherits from both TimestampedModel
and UUIDModel
. It will also automatically add the created_at
and updated_at
fields to the model, as well as the id field using UUID.
Conclusion
In this article, we've learned how to create a set of base models that can be used as the foundation for all of our other models. We've also learned how to combine these base models into a single abstract base model class that can be used as the foundation for all of our other models.