Django Models

To tackle the above-said problem Django provides something called Django Models.

 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 the database. Django models simplify the tasks and organize tables into models. Generally, each model maps to a single database table.

This section revolves around how one can use Django models to store data in the database conveniently. Moreover, we can use the 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.

Syntax:

from django.db import models       
class ModelName(models.Model):
       field_name = models.Field(**options)

Example:

Python3




# import the standard Django Model
# from built-in library
from django.db import models
from datetime import datetime
  
class GeeksModel(models.Model):
  
    # Field Names
    title = models.CharField(max_length=200)
    description = models.TextField()
    created_on = models.DateTimeField(default=datetime.now)
    image = models.ImageField(upload_to="images/%Y/%m/%d")
  
    # rename the instances of the model
    # with their title name
    def __str__(self) -> str:
        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.

Now let’s see how to add data to our newly created SQLite table.

Django CRUD – Inserting, Updating, and Deleting Data

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:

Python3




from gfg_site_app.models import GeeksModel
  
obj = GeeksModel(title="w3wiki",
   description="GFG is a portal for computer science students")
obj.save()


Retrieving objects

To retrieve all the objects of a model, we write the following command:

Python3




GeeksModel.objects.all()


Output:

<QuerySet [<GeeksModel: w3wiki>]>

Modifying existing objects

We can modify an existing object as follows:

Python3




obj = GeeksModel.objects.get(id=1)
obj.title = "GFG"
obj.save()
  
GeeksModel.objects.all()


Output:

<QuerySet [<GeeksModel: GFG>]>

Deleting objects

To delete a single object, we need to write the following commands:

Python3




obj = GeeksModel.objects.get(id=1)
obj.delete()
  
GeeksModel.objects.all()


Output:

(1, {'gfg_site_app.GeeksModel': 1})
<QuerySet []>

Refer to the below articles to get more information about Django Models – 

Python Web Development With Django

Python Django is a web framework that allows to quickly create efficient web pages. Django is also called batteries included framework because it provides built-in features such as Django Admin Interface, default database – SQLite3, etc. When you’re building a website, you always need a similar set of components: a way to handle user authentication (signing up, signing in, signing out), a management panel for your website, forms, a way to upload files, etc. Django gives you ready-made components to use.

Similar Reads

Why Django Framework?

Excellent documentation and high scalability. Used by Top MNCs and Companies, such as Instagram, Disqus, Spotify, Youtube, Bitbucket, Dropbox, etc. and the list is never-ending. Easiest Framework to learn, rapid development, and Batteries fully included. Django is a rapid web development framework that can be used to develop fully fleshed web applications in a short period of time. The last but not least reason to learn Django is Python, Python has a huge library and features such as Web Scraping, Machine Learning, Image Processing, Scientific Computing, etc. One can integrate all this with web applications and do lots and lots of advanced stuff....

Django Architecture

Django is based on MVT (Model-View-Template) architecture which has the following three parts –...

Setting up the Virtual Environment

Most of the time when you’ll be working on some Django projects, you’ll find that each project may need a different version of Django. This problem may arise when you install Django in a global or default environment. To overcome this problem we will use virtual environments in Python. This enables us to create multiple different Django environments on a single computer. To create a virtual environment type the below command in the terminal....

Installing Django

We can install Django using the pip command. To install this type the below command in the terminal....

Starting the project

To initiate a project of Django on Your PC, open Terminal and Enter the following command...

Project Structure

A Django Project when initialized contains basic files by default such as manage.py, view.py, etc. A simple project structure is enough to create a single-page application. Here are the major files and their explanations. Inside the geeks_site folder ( project folder ) there will be the following files-...

Creating an app

Django is famous for its unique and fully managed app structure. For every functionality, an app can be created like a completely independent module. For example, if you are creating a Blog, Separate modules should be created for Comments, Posts, Login/Logout, etc. In Django, these modules are known as apps. There is a different app for each task. Benefits of using Django apps –...

Django Views

...

Django URL Patterns

...

Django Models

A view function is a Python function that takes a Web request and returns a Web response. This response can be the HTML contents of a Web page, or a redirect, or a 404 error, or an XML document, or an image, anything that a web browser can display. Django views are part of the user interface — they usually render the HTML/CSS/Javascript in your Template files into what you see in your browser when you render a web page....

Uploading Images in Django

...

Render a model in Django Admin Interface

In Django, each view needs to be mapped to a corresponding URL pattern. This is done via a Python module called URLConf(URL configuration). Every URLConf module must contain a variable urlpatterns which is a set of URL patterns to be matched against the requested URL. These patterns will be checked in sequence until the first match is found. Then the view corresponding to the first match is invoked. If no URL pattern matches, Django invokes an appropriate error handling view....

Connecting Django to different Database

...

Django Templates

...

Django Forms

To tackle the above-said problem Django provides something called Django Models....

More on Django

...

Django Projects

...