Django Models Deeper: Mastering Advanced Features and Practical Uses

Hello, everyone! Fundamentals of Django Modelsand go deeper with us. If you've used Django, you know how powerful Models can be, but today we're going to go beyond the basics, Django We're going to explore the Models deep features.
Leverage custom managers, abstract models, and multiple databases and other real-world techniques will be explained in a simple way with code examples. By the end of this post, you'll be able to master Django Models!

1. Django Models in depth: Custom Manager
Beyond the managers Django provides out of the box, custom managers give you more flexibility to retrieve data. For example, let's create a manager that only retrieves data that meets certain conditions.

from django.db import models
class PublishedManager(models.Manager):
def get_queryset(self):
return super().get_queryset().filter(status='published')
class Post(models.Model):
title = models.CharField(max_length=200)
content = models.TextField()
status = models.CharField(max_length=10, choices=[('draft', 'Draft'), ('published', 'Published')])
objects = models.Manager() # default manager
published = PublishedManager() # custom manager
def __str__(self):
return self.titleCode commentary
class PublishedManager(models.Manager):
- Django's
Managerto define a custom manager class.- This class is designed to allow you to apply specific conditions to a database lookup and return a custom queryset.
def get_queryset(self):
get_querysetmethod is responsible for returning the query set.return super().get_queryset().filter(status='published')
- The default query set (
super().get_queryset()) to add a filter to thestatusIf the field value is'published'Set to lookup only data that is- This method allows you to use the
publishedYou can selectively manage only the data in a state.objects = models.Manager()
- Define the default manager for the model.
objectsprovides a default queryset that includes all data.- It can be used with custom managers to provide additional ways to view data in your model.
published = PublishedManager()
- Connect a custom manager to your model to create a
status='published'Define a manager that returns a query set with conditions applied.- With this manager, you can use the
Post.published.all()to easily look up data that meets specific conditions.class Post(models.Model):
- A model class that manages blog posts.
- The main fields are
title: The title of the post (CharField), with a maximum length of 200 characters.content: The field that stores the body content of the post (TextField).status: Post status (draftorpublished) to store the data.choicesoption to limit the possible values.def __str__(self):
- When representing an object as a string, you can use a post's title (
title) to be returned.- For example, from the Django admin page or shell, you can use the
PostWhen you output an object, it displays a title.
2. Django Models Deeper: Abstract Model
Abstract models are useful for defining fields that are used in common across multiple models. Models that inherit from an abstract model will automatically include the fields from the abstract model.

class TimeStampedModel(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
abstract = True
class Post(TimeStampedModel):
title = models.CharField(max_length=200)
content = models.TextField()
def __str__(self):
return self.titleCode commentary
class TimeStampedModel(models.Model): Defines an abstract model class.created_at = models.DateTimeField(auto_now_add=True): Automatically save the time the model was created.updated_at = models.DateTimeField(auto_now=True): Automatically save the time the model was updated.class Meta: abstract = True: Declares that this model is an abstract model.class Post(TimeStampedModel):TimeStampedModelwhich inherits fromPostDefine a model.
3. Deepening Django Models: Utilizing Multiple Databases
Django can use multiple databases at the same time. For example, you can have a read-only database and a write-only database.
class User(models.Model):
name = models.CharField(max_length=100)
email = models.EmailField()
class Meta:
db_table = 'user'
using = 'default' use # default database
class Log(models.Model):
action = models.CharField(max_length=100)
timestamp = models.DateTimeField(auto_now_add=True)
class Meta:
db_table = 'log'
using = 'logs_db' # using a separate databaseCode commentary
class User(models.Model):Meta Classes:
- Manage user dataA Django model class for creating and manipulating Django models.
- It primarily stores username and email information.
- The main fields are
name: A character field that can store up to 100 characters (CharField).EmailField), validation is automatically applied.
db_table = 'user':
- Set the name of the table to use in the database to
'user'to the default.- The default rule for automatically generating table names (
appname_modelname) instead of the specified name.using = 'default':
- This model is based on the Django project's default database (
default) in the following example.
class Log(models.Model):Meta Classes:
- Manage log dataA Django model class for creating and manipulating Django models.
- The main fields are
action: A character field that can store up to 100 characters (CharField), which stores a description of a specific action (e.g. "login", "logout").timestamp: A date-time field that stores when the action occurred (DateTimeField).
auto_now_add=True: Automatically save the current time when the object is first created.
db_table = 'log':
- Set the name of the table to use in the database to
'log'to the default.using = 'logs_db':
- This model is based on the
'logs_db'called Separate databasesto use the- The project's configuration file (
settings.py) in the'logs_db'must be defined.
Finalize
Now that you know the deeper features of Django Models, you should be able to use them more effectively. If you have any further questions, please leave them in the comments. Let's learn together! 😊
# Glossary
- Custom ManagerA customized manager that allows you to retrieve only data that meets certain conditions.
- Abstract ModelA model that defines fields that are used in common across multiple models.
- Multiple DatabasesA technique for using multiple databases simultaneously in one application.






