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 –
- Django Models
- ORM – Inserting, Updating & Deleting Data
- Basic App Model – Makemigrations and Migrate
- model data types and fields list
- Add the slug field inside Django Model
- Intermediate fields in Django
- Uploading images in Django
- Change Object Display Name using __str__ function – Django Models
- Built-in Field Validations – Django Models
- Custom Field Validations in Django Models
- How to use Django Field Choices ?
- Overriding the save method – 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.