Create Models in Django

Models in django

A model is a class that represents a table in our database. Every attribute of the class is a field of the table. Models are defined in the directory : appname/ In our example : accounts/

Open the and create a class with the name of the table you want to create in the database and add the fields in that class as shown below:

class Student(models.Model):
    name = models.CharField(max_length=191null=True)
    age = models.CharField(max_length=20null=True)
    course = models.CharField(max_length=191null=True)
    phone = models.CharField(max_length=191null=True)
    email = models.CharField(max_length=191null=True)
    dateCreated = models.DateTimeField(auto_now_add=Truenull=True)

    def __str__(self): #this is to show the name in the admin panel, you will understand in the next tutorial
        return #even if you dont write this function, you will not face any issues 

Now run the following command to create the migration:

py makemigrations 

You will get the migrations in the appname/migrations folders.

Open the migration file and you will be able to see all the fields you had created in the models.

class Migration(migrations.Migration):

    dependencies = [

    operations = [
                ('id', models.AutoField(auto_created=Trueprimary_key=Trueserialize=Falseverbose_name='ID')),
                ('name', models.CharField(max_length=191null=True)),
                ('age', models.CharField(max_length=20null=True)),
                ('course', models.CharField(max_length=191null=True)),
                ('phone', models.CharField(max_length=191null=True)),
                ('email', models.CharField(max_length=191null=True)),
                ('dateCreated', models.DateTimeField(auto_now_add=Truenull=True)),

Now you have to register the model in the

Open the file and add the below code:

from django.contrib import admin
from .models import Student
# Register your models here.

Now migrate the table using the following command : 

$ py migrate

Now you can check your database. The table and the table structure will be visible there. 

You can see the newly created table in the admin panel under the appname heading(accounts) by going to the below given url in your browser: 


Tags: Funda of web it Django tutorials, Django tutorials, Django tutorials funda, django for beginners, how to make migrations in django, django models, how to make models in django, make models and migrations in django, how to make migrations and models in django 

© Copyright - 2018 - 2023 | All rights reserved at Funda of Web IT