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/models.py. In our example : accounts/models.py.

Open the models.py 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 self.name #even if you dont write this function, you will not face any issues 

Now run the following command to create the migration:

py manage.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 = [
        migrations.CreateModel(
            name='Student',
            fields=[
                ('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 admin.py.

Open the admin.py file and add the below code:

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

admin.site.register(Student)

Now migrate the table using the following command : 

$ py manage.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: 

http://localhost:8000/admin/ 

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 - 2021 | All rights reserved at Funda of Web IT