DEV Community

Cover image for Models In Django

Models In Django

ketanip profile image KetanIP Originally published at Updated on ・1 min read

This is part of the series Django For Beginners we are going to see about apps in app and we will see about models in django in this part.

What are models ?

Models play an important role in django, it makes it what it is. Models is the way to represent our database in a pretty form. We can also change databases without any changes to models in django, and we use these models to query our database. Models make life easy.

We define models for our application in apps in file. Now let's see the example, in this example we are going to design a model for a blog post and tags associated with blog post. In real-life scenario you can also you libraries such as django-taggit for tagging the blog post and to do the heavy lifting for us. Now let's see the example,

from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User

class Blog(models.Model):
    title = models.CharField(max_length=250)
    post  = models.TextField()
    slug  = models.SlugField()
    tags  = models.ManyToManyField('Tag', blank=True)
    createdAt = models.DateTimeField(
    createdBy = models.ForeignKey(User, on_delete=models.CASCADE)

class Tag(models.Model):
    tag = models.CharField(max_length=250)
    createdAt = models.DateTimeField(auto_now=True)
    blogs = models.ManyToManyField(Blog, blank=True)

Enter fullscreen mode Exit fullscreen mode

Sorry to interrupt you but I want to tell you one thing that I have started a small blog you may continue reading it here it will help me a lot.


Editor guide