This is our fifth article on Django, in this article we are going to talk about Django Models Introduction & Example, also you can read the other articles on Django in these links.
Read Django Articles
1: Django Introduction & Installation
4: Django Templates Introduction
What are Django Models ?
The typical way for Django applications to interact with data is using Django models. A Django model is an object-oriented Python class that represents the characteristics of an entity. for example an entity can be a product, company or something else. Django models often serve as the building blocks for Django projects. Once you have a set of Django models representing an application’s entities, Django models can also serve as the basis to simplify the creation of other Django constructs that operate with data (e.g forms, class-based views, REST services, Django admin pages), so it means that Django Models play an important role in a Project.
OK first of all you need to create project in Django, we have already covered the creation of the Django project in our previous article Django Introduction & Installation. but you can use this command for creating of Django Project.
1 |
django-admin startproject MyProject |
After creation of the Django Project, you need to migrate your Django Project.
1 2 |
cd MyProject python manage.py migrate |
Now we need to create an App, you can read the complete article about Django Apps in this link Django Apps & URL Routing . i have named my App as news, but you can name it what ever you want.
1 |
python manage.py startapp news |
Also you need to add your newly created app in the Django settings.py INSTALLED_APPS. make sure that always do this process after creating a new App.
1 2 3 4 5 6 7 8 9 10 |
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'contact', 'news', ] |
Create Django Models
Django models are stored in models.py files located inside Django apps. As soon as you create a Django app, an empty models.py file is added to the app for future use. If you’re unfamiliar with the term Django app, you can read this article Django Apps & URL Routing .
1 2 3 4 5 6 7 8 9 10 11 12 13 |
from django.db import models # Create your models here. class News(models.Model): author = models.CharField(max_length=100) title = models.CharField(max_length=100) description = models.TextField() def __str__(self): return self.title |
basically we have created a simple model, so you can see that after our main News class, we have three fields with models.CharField data type that qualify the field as character strings. further restricting the acceptable values for each field is the max_length argument for models.CharField (e.g., max_length=100 indicates the maximum length for the character field is 100 characters). and also there are different data types that you can use in Django models package. the id field is a Django AutoField data type, which behind the scenes creates an integer table column
that increments automatically. For example, when you create the first News record, the id field is set to 1 by the database, for the second News record the database sets the id field to 2, and so on.
Django Model Migrations
So after adding a new model you need to do migrate and also make migrations, the make migration create our model tables and the migrate add our model tables in to database, as you know by default django comes with sqlite database configuration, but in the further articles we will learn , how you can add other databases in Django.
1 |
python manage.py makemigrations |
After doing this command you will see this output in your terminal.
1 2 3 |
Migrations for 'news': news\migrations\0001_initial.py - Create model News |
And if you see your migrations folder and open 0001_initial.py file, this is our model.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
# Generated by Django 3.0 on 2020-06-04 06:00 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='News', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('author', models.CharField(max_length=100)), ('title', models.CharField(max_length=100)), ('description', models.TextField()), ], ), ] |
So after that we need to add our this model in to the database, we are using sqlite database, you can use this command.
1 |
python manage.py migrate |
After doing that commands you will see this output, and our model is successfully added to our sqlite database.
1 2 3 4 |
Operations to perform: Apply all migrations: admin, auth, contenttypes, news, sessions Running migrations: Applying news.0001_initial... OK |
Django Models Method
All Django models inherit a series of methods for operations that include saving, deleting, validating, loading, and applying custom logic to model data.
save() method
The save() method offers one of the most common operations for Django models: to save (i.e., create or update) a record to a database.
delete() method
The delete() method is used to eliminate a record from the database through a reference.
OK now as you remember in one of our articles Django Creating Super User, we have created an administration panel, now we need to add our this model in our admin panel, for creation of the super user you can use this command.
1 |
python manage.py createsuperuser |
Now you need to open your admin.py from your news app, and add your model in their like this .
1 2 3 4 5 6 |
from django.contrib import admin from .models import News # Register your models here. admin.site.register(News) |
Now if you run the project and go to http://localhost:8000/admin/, you will see your model in their.
Working with Django Shell
Now we are going to add some data to our database model, we are going to use Django Shell, so it is a good feature of django that you can interact with your django models from terminal using Django Shell. first of you need to just change directory to your project, and after that run this command.
1 |
python manage.py shell |
So now let’s add a data in our model
1 2 3 4 5 6 |
In [5]: from news.models import News In [6]: n = News(author = "Codeloop", title = "Codeloop Website", description = "Co ...: deloop description") In [7]: n.save() |
Now if you see your model, you can see that we have a new record in our database
1 2 |
In [8]: News.objects.all() Out[8]: <QuerySet [<News: Codeloop Website>]> |
Subscribe and Get Free Video Courses & Articles in your Email