1. About django model
In Django, a model is a Python class that represents a database table. It is a key component of Django's Object-Relational Mapping (ORM) system, which allows you to interact with the database using Python code instead of writing raw SQL queries.
A Django model is defined as a subclass of the django.db.models.Model class. Each attribute of the model class represents a field in the corresponding database table. Django provides various field types, such as CharField, IntegerField, DateField, ForeignKey, and more, to define the different types of data that can be stored in the fields.
By defining a model, you can perform database operations like creating, retrieving, updating, and deleting records, as well as executing complex queries using a high-level API. Django's ORM handles the underlying SQL generation, data validation, and database transactions for you, making it easier to work with databases in a Pythonic way.
2. Fields type in django model
Django offers a wide range of field types to cater to different data requirements when defining a Django model. The field types provide flexibility and versatility for handling different types of data within a Django model. By choosing the appropriate field types, you can effectively capture and store the desired information in your Django application. Here are several commonly used field types:
- AutoField: An integer field that automatically increments for each new object added to the database. Typically used as the primary key for a model.
- CharField: Stores character data, such as strings. The maximum length can be specified using the max_length parameter.
- IntegerField: Stores integers.
- FloatField: Stores floating-point numbers.
- BooleanField: Stores boolean values (True or False).
- DateField: Stores dates. Requires a date value in the 'YYYY-MM-DD' format.
- DateTimeField: Stores dates and times. Requires a datetime value in the 'YYYY-MM-DD HH:MM:SS' format.
- EmailField: Stores email addresses. Performs basic validation to ensure a properly formatted email address.
- FileField: Stores uploaded files. Requires a file upload widget in the form.
- ImageField: Stores uploaded image files. Inherits from FileField and includes additional validation for image files.
- ForeignKey: Defines a many-to-one relationship between two models. Creates a foreign key in the database to establish the relationship.
- ManyToManyField: Defines a many-to-many relationship between two models. Creates an intermediate table in the database to manage the relationship.
- TextField: Stores large amounts of text data.
- URLField: Stores URLs. Performs basic validation to ensure a properly formatted URL.
- UUIDField: Stores universally unique identifiers (UUIDs).
The field types provide flexibility and versatility for handling different types of data within a Django model. By choosing the appropriate field types, you can effectively capture and store the desired information in your Django application.
3. Creation of a Django model
In this paragraph we will create a django model called 'Student' with the fields: 'name', 'email', 'phone', and 'section'
To do this, you can follow these steps:
- Step 1: Create a django project called: 'mysite' and make migration
- step 2: Create an app called 'myapp'
- step 2: pen the file myapp/models.py in your Django app
- Step 3: Import the necessary modules:
1 |
from django.db import models |
- Step 4: Define the 'Student' model with the desired fields:
1 2 3 4 5 6 7 8 |
class Student(models.Model): name = models.CharField(max_length=100) email = models.EmailField() phone = models.CharField(max_length=20) section = models.CharField(max_length=50) def __str__(self): return self.name |
In this example:
- The 'Student' model: has four fields 'name', 'email', 'phone', and 'section'.
- The 'name' field: is defined as a CharField with a maximum length of 100 characters.
- The 'email' field: is an EmailField for storing email addresses.
- The 'phone' field: is a CharField with a maximum length of 20 characters.
- The 'section' field: is also a CharField with a maximum length of 50 characters.
- The __str__ method: is defined to return a human-readable string representation of a 'Student' object, which in this case is the name of the student.
Once you have defined the model, you can perform various database operations such as creating, retrieving, updating, and deleting 'Student' objects using Django's ORM. Remember to run migrations simply type in the command:
1 |
python manage.py makemigrations |
and
1 |
python manage.py migrate |
to create the corresponding database table for the 'Student' model.
4. Adding model in django admin area
In order to be able to manage the model that we have just created, it is therefore necessary to load it in the site's admin area. To do this, simply edit the myapp/admin.py file by adding the lines of code:
1 2 3 4 5 |
from django.contrib import admin from .models import Student # register the site in django admin area admin.site.register(Student) |
Now if you access the site's admin area, you will find the Student section, which gives you the possibility of editing and modification:
5. Improved model management within the admin area
We can now improve the display of records in the admin area by displaying the list of names, emails, sections … For this purpose we must import the admin module from django.contrib on the models.py file:
1 |
from django.contrib import admin |
We then create a class in the models.py file which inherits from the admin.ModelAdmin class which allows to indicate the list of attributes to display and the attributes according to which the filtering of the records is performed:
1 2 3 |
class StudentAdmin(admin.ModelAdmin): list_display = ('name' , 'email' , 'section') list_filter = ('name',) |
Here is the final code of the models.py file:
1 2 3 4 5 6 7 8 9 10 11 |
from django.contrib import admin from django.db import models class Student(models.Model): name = models.CharField(max_length=100) email = models.EmailField() phone = models.IntegerField(max_length=20) section = models.CharField(max_length=50) class StudentAdmin(admin.ModelAdmin): list_display = ('name' , 'email' , 'section') list_filter = ('name',) |
There are now some modifications to the level of the admin.py files in which we must import and save the StudentAdmin class that we just created:
1 2 3 4 |
from django.contrib import admin from studentsApp.models import Student , StudentAdmin admin.site.register(Student , StudentsAdmin) |
And finally, if you access the admin area you will see that there is actually an improvement in the display of results showing the list of names, emails, sections …
Younes Derfoufi
CRMEF OUJDA