Django Models

11 Apr, 2022
A Django model is the built-in feature that Django uses to create tables, their fields, and various constraints. In short, Django Models is the SQL of Database one uses with Django. SQL (Structured Query Language) is complex and involves a lot of different queries for creating, deleting, updating or any other stuff related to database. Django models simplify the tasks and organize tables into models. Generally, each model maps to a single database table. This article revolves about how one can use Django models to store data in the database conveniently. Moreover, we can use admin panel of Django to create, update, delete or retrieve fields of a model and various similar operations. Django models provide simplicity, consistency, version control and advanced metadata handling. Basics of a model include –  
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; see Making queries.
Example –  
Python3
from django.db import models # Create your models here.class GeeksModel(models.Model):    title = models.CharField(max_length = 200)    description = models.TextField()
Django maps the fields defined in Django models into table fields of the database as shown below.  
 
To use Django Models, one needs to have a project and an app working in it. After you start an app you can create models in app/models.py. Before starting to use a model let’s check how to start a project and create an app named geeks.py 
Refer to the following articles to check how to create a project and an app in Django.  
How to Create a Basic Project using MVT in Django?
How to Create an App in Django ?
 
Syntax  
from django.db import models
        
class ModelName(models.Model):
        field_name = models.Field(**options)
To create a model, in geeks/models.py Enter the code,  
Python3
# import the standard Django Model# from built-in libraryfrom django.db import models # declare a new model with a name "GeeksModel"class GeeksModel(models.Model):        # fields of the model    title = models.CharField(max_length = 200)    description = models.TextField()    last_modified = models.DateTimeField(auto_now_add = True)    img = models.ImageField(upload_to = "images/")         # renames the instances of the model        # with their title name    def __str__(self):        return self.title
Whenever we create a Model, Delete a Model, or update anything in any of models.py of our project. We need to run two commands makemigrations and migrate. makemigrations basically generates the SQL commands for preinstalled apps (which can be viewed in installed apps in settings.py) and your newly created app’s model which you add in installed apps whereas migrate executes those SQL commands in the database file. So when we run,  
Python manage.py makemigrations
SQL Query to create above Model as a Table is created and  
 Python manage.py migrate
creates the table in the database.Now we have created a model we can perform various operations such as creating a Row for the table or in terms of Django Creating an instance of Model. To know more visit – Django Basic App Model – Makemigrations and Migrate  
To render a model in Django admin, we need to modify app/admin.py. Go to admin.py in geeks app and enter the following code. Import the corresponding model from models.py and register it to the admin interface. 
Python3
from django.contrib import admin   # Register your models here.from .models import GeeksModel   admin.site.register(GeeksModel)
Now we can check whether the model has been rendered in Django Admin. Django Admin Interface can be used to graphically implement CRUD (Create, Retrieve, Update, Delete).  
To check more on rendering models in django admin, visit – Render Model in Django Admin Interface 
Django lets us interact with its database models, i.e. add, delete, modify and query objects, using a database-abstraction API called ORM(Object Relational Mapper). We can access the Django ORM by running the following command inside our project directory. 
python manage.py shell
Adding objects. To create an object of model Album and save it into the database, we need to write the following command: 
>>>> a = GeeksModel(

         title = "GeeksForGeeks",  

         description = "A description here",

         img = "geeks/abc.png"

         )

>>> a.save()
Retrieving objects To retrieve all the objects of a model, we write the following command: 
>>> GeeksModel.objects.all()
<QuerySet [<GeeksModel: Divide>, <GeeksModel: Abbey Road>, <GeeksModel: Revolver>]>
Modifying existing objects We can modify an existing object as follows: 
>>> a = GeeksModel.objects.get(id = 3)
>>> a.title = "Pop"
>>> a.save()
Deleting objects To delete a single object, we need to write the following commands: 
>>> a = Album.objects.get(id = 2)
>>> a.delete()
To check detailed post of Django’s ORM (Object) visit Django ORM – Inserting, Updating & Deleting Data 
Built-in Field Validations in Django models are the default validations that come predefined to all Django fields. Every field comes in with built-in validations from Django validators. For example, IntegerField comes with built-in validation that it can only store integer values and that too in a particular range. Enter the following code into models.py file of geeks app.  
Python3
from django.db import modelsfrom django.db.models import Model# Create your models here. class GeeksModel(Model):    geeks_field = models.IntegerField()     def __str__(self):        return self.geeks_field
After running makemigrations and migrate on Django and rendering above model, let us try to create an instance using string “GfG is Best“.  
You can see in the admin interface, one can not enter a string in an IntegerField. Similarly every field has its own validations. To know more about validations visit, Built-in Field Validations – Django Models 
 
Change Object Display Name using __str__ function – Django Models  
Custom Field Validations in Django Models
Django python manage.py migrate command
Django App Model – Python manage.py makemigrations command
Django model data types and fields list
How to use Django Field Choices ?
Overriding the save method – Django Models
 
The most important part of a model and the only required part of a model is the list of database fields it defines. Fields are specified by class attributes. Here is a list of all Field types used in Django.  
 
 
Django also defines a set of fields that represent relations.
 
 
Field Options are the arguments given to each field for applying some constraint or imparting a particular characteristic to a particular Field. For example, adding an argument null = True to CharField will enable it to store empty values for that table in relational database. Here are the field options and attributes that an CharField can use.
 
 
namankukreja01
Django-models
Python Django
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Iterate over a list in Python
Read JSON file using Python
Python map() function
How to iterate through Excel rows in Python?
Enumerate() in Python
Adding new column to existing DataFrame in Pandas
Python OOPs Concepts
Different ways to create Pandas Dataframe
How to get column names in Pandas dataframe
Stack in Python