Django Models

django model databse and sql query

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:

  1. AutoField: An integer field that automatically increments for each new object added to the database. Typically used as the primary key for a model.
  2. CharField: Stores character data, such as strings. The maximum length can be specified using the max_length parameter.
  3. IntegerField: Stores integers.
  4. FloatField: Stores floating-point numbers.
  5. BooleanField: Stores boolean values (True or False).
  6. DateField: Stores dates. Requires a date value in the 'YYYY-MM-DD' format.
  7. DateTimeField: Stores dates and times. Requires a datetime value in the 'YYYY-MM-DD HH:MM:SS' format.
  8. EmailField: Stores email addresses. Performs basic validation to ensure a properly formatted email address.
  9. FileField: Stores uploaded files. Requires a file upload widget in the form.
  10. ImageField: Stores uploaded image files. Inherits from FileField and includes additional validation for image files.
  11. ForeignKey: Defines a many-to-one relationship between two models. Creates a foreign key in the database to establish the relationship.
  12. ManyToManyField: Defines a many-to-many relationship between two models. Creates an intermediate table in the database to manage the relationship.
  13. TextField: Stores large amounts of text data.
  14. URLField: Stores URLs. Performs basic validation to ensure a properly formatted URL.
  15. 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:

  • Step 4: Define the 'Student' model with the desired fields:

In this example:

  1. The 'Student' model: has four fields 'name', 'email', 'phone', and 'section'.
  2. The 'name' field: is defined as a CharField with a maximum length of 100 characters.
  3. The 'email' field: is an EmailField for storing email addresses.
  4. The 'phone' field: is a CharField with a maximum length of 20 characters.
  5. The 'section' field: is also a CharField with a maximum length of 50 characters.
  6. 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:

and

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:

Now if you access the site's admin area, you will find the Student section, which gives you the possibility of editing and modification:

add model in django admin

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:

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:

Here is the final code of the models.py file:

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:

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 …

improve model management in django admin area

 

Younes Derfoufi
CRMEF OUJDA

Leave a Reply