Django Models

Django Models

Django is a python web framework for building web applications.

Django Models is one of the key components of Django Web Application.

It helps us to create a database for our app without writing queries ourselves.

Some key concepts of Django models are model fields and relationships.

Model fields :

-> Model fields are the attributes of the Django model.

-> They indicate the data types.

-> Eg. CharField, IntegerField, ForeignKey, etc.

Relationships :

-> Django models can have relationships with other models.

-> One-to-One: One table record can relate to one record in another table.

-> One-to-Many: One table record can relate to many records in another table.

-> Many-to-Many: Multiple records in a table are associated with multiple records in another table.

Let's create a model:

Make sure to add your app name in settings.py.

We have created a blog project and in it created a blog app.

In this blog app, write the above code in models.py.

Is our model ready? the answer is no because you can see the migrations folder over there. If your migrations folder is empty then your models were not created.

So, to apply the migrations run the below commands.

Guess what our model is ready.

There is one more thing, Django comes with a built-in admin panel.

To access it we need to create a superuser by using the following command.

Make sure to start the server.

After doing all of this, go to your browser and open port 8000. (http://127.0.0.1:8000/admin/)

Here, it allows you to create, read, update and delete records in your application's database.