Exploring best practices for working with models and ORM
Django’s official documentation is a very detailed guide on how to work with models and ORM, and it helps you write complicated queries using ORM. But when you create real-world applications, it is more than just writing good queries; there is a lot of nitty-gritty that you should know or get to know after making mistakes yourself. In this section, we are going to learn about all those small tricks that can help us work better with Django models and ORM.
Use base models
Abstract base models are one of the most preferred model inheritances in Django. We should create common base models whenever we find duplicates of the model attributes. One of the most useful base models that I have found is TimeStampedBaseModel
, which has created_at
and updated_at
fields. Using this base model to create any model will automatically add the created at
and updated at
timestamp field; for example, whenever someone creates a DemoModel...