In this Django REST Framework we are going to learn about Django Models, so 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.
Now we are going to create our simple model, so open your models.py file in your api app, as we have already said the Django Models are basically regular Python classes that extends from models.Model, we have three fields in our model, the first one is id that is auto created and you don’t need to create that, the second field is title field and it is a Character field with the max length of 100, the the third one is our description field and that a Text Field.
1 2 3 4 5 6 7 8 9 10 11 12 |
from django.db import models # Create your models here. class Article(models.Model): title = models.CharField(max_length=100) description = models.TextField() def __str__(self): return self.title |
After creating of the models in Django, you need to do migrations and migrate.
1 |
python manage.py makemigrations |
This will be the result and you can see that we have created our model blue print, but right now it is not available in our SQLite database.
1 2 3 |
Migrations for 'api': api\migrations\0001_initial.py - Create model Article |
Now we want to add our model to the SQLite database.
1 |
python manage.py migrate |
If you see your SQLite database in the SQLiteStudio, you will see that we have our table.
Let’s add our this model in our Django Super User or we can say Django Admin Panel, you can open admin.py file in your api app.
1 2 3 4 5 6 |
from django.contrib import admin from .models import Article # Register your models here. admin.site.register(Article) |
Now go to http://localhost:8000/admin/ and you can see that we have our model.