Instagram
youtube
Facebook
Twitter

Django Model

Django Model

The Django model is a class that is used to store essential fields and methods. Each model has its table in the database. Django uses SQLite as its default database. A database is the collection of data. 

Let us understand the whole concept of the Django model with some practical work.

Creating a contact form in the Django model

Open the models.py file of your app and write the code given below.

class Contact(models.Model):
    name = models.CharField(max_length=50)
    email= models.CharField(max_length=50)
    phone = models.CharField(max_length=12)
    message= models.TextField()

Here, we have created a class in Django models. Contact is our model name. models.The model means our Contact is a model by, this Django knows that it should be saved in the database.

Name, email, phone, and message are our class attributes and every attribute refers to a different database column. Here, the models, CharField indicates that our class attribute will store a limited number of characters and max_length refers to the maximum length. TextField is used to store text without a limit.

If you want to learn more about Django models please go through the official Django documentation(Django documentation)

Creating a table for our model in the database

To inform Django that we have made some changes in the database. Use the following command.

\Codersdaily\project1> python manage.py makemigrations

Now, Django has prepared a migration file for us. To apply that in the database use the given command.

\Codersdaily\project1> python manage.py migrate

So, our Django model is now successfully added to the database. But, a new question arises: how can we view the data saved in our Django model? That's where the concept of Django admin comes in.