In Django, Model Managers are classes that act as the interface between Django models and the database. A Model can have any number of managers and using these managers we can extend the functionality of the model.
An Introduction to Django Model Managers, we’ll start from the default model manager and then go through creating and customizing model managers.
In this post, we’ll take the example of a BlogModel
and then create a custom model manager for it.
The first step is to create an app and name it blogs
and make BlogModel
in file models.py
.
from datetime import datetime
from django.db import models
from django.contrib.auth.models import User
class BlogModel(models.Model):
BLOG_STATUS = (
('PUBLISH', 'Publish'),
('DRAFT', 'Draft'),
)
blog_id = models.AutoField(primary_key=True)
user = models.ForeignKey( User, on_delete=models.CASCADE, related_name='blogs' )
title = models.CharField(max_length=255)
content = models.TextField(blank=True, null=True)
status = models.CharField(max_length=7, choices=BLOG_STATUS)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta():
db_table = 'blogs'
verbose_name = 'Blog'
verbose_name_plural = 'Blogs'
def __str__(self):
return self.title
In BlogModel
field user
shares ForeignKey
relationship with Django’s built-in AUTH_USER_MODEL
.
#django framework #python #django