Open In App

Django Models | Set – 1

Improve
Improve
Like Article
Like
Save
Share
Report

Prerequisites : Django Creating apps

Models –

According to Django Models, A model is the single, definitive source of information about your data. It contains the essential fields and behaviors of the data you’re storing. Generally, each model maps to a single database table.

The basics:

  • Each model is a Python class that subclasses django.db.models.Model.
  • Each attribute of the model represents a database field.
  • With all of this, Django gives you an automatically-generated database-access API.

Django models are used as a structure to define fields and their types which will be saved in the database. Whatever changes we want to make in the database and want to store them in the database permanently are done using Django Models. A table for a phone in the database can be imagined as:
A database table for phone

Create table in database using Django –

We need to create a new app named product so that we can define all properties of phone described in the above-provided image. Open your terminal and run following command:

python manage.py startapp product

Now, our directory will be:
Directory after creating product app
After creating the app, don’t forget to mention it in geeks_site/settings.py under INSTALLED_APPS.

Installed apps after product

Also, register it with admin by adding following line of code to product/admin.py. By registering it with admin, you make sure that admin of the site will be aware that new table schema for database has been prepared.




   
from django.contrib import admin
  
# Register your models here.
from product.models import Phone
  
admin.site.register(Phone)


Now, navigate to product/models.py. You will see a file with following lines:




   
from django.db import models
  
# Create your models here.


We use a python class to define models which inherit parent class named Model defined in django.db.models package.

Add the following lines of code to this file:




   
  
from django.db import models
  
# Create your models here.
class Phone(models.Model):
    Price = models.IntegerField()
    RAM = models.IntegerField()
    ROM = models.IntegerField()
    Front_camera = models.IntegerField()
    Rear_camera = models.IntegerField()
    Battery = models.IntegerField()
    Screen_size = models.DecimalField(max_digits = 2, decimal_places = 1)
    Color = models.CharField(max_length = 120)
    Quantity = models.IntegerField()




Last Updated : 21 Jun, 2019
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads