Let's Learn Django #6: Using Database & Admin Panel
Tags: webdev, django, beginners, python
Published: 2023-07-22 20:31:01

In the last blog, we discussed how can we use Django templating to the fullest. In this blog, we will discuss how can we use databases and handle our data in Django.

## **Introduction to Django databases**

I am hoping everyone knows what a database is, but for those who don't know, it's a structured way we store our data.

Django supports many relational databases like SQLite, MySQL, Postgres etc.

By default, Django uses SQLite, but feel free to use any according to your preference/use case.

We will also be using SQLite in this blog.

To know more about how to use different databases, check out the following Django documentation: [https://docs.djangoproject.com/en/4.2/ref/databases/](https://docs.djangoproject.com/en/4.2/ref/databases/)

## What are models?

Models are basically Python classes that represent a table in the database. Each attribute of the class represents a field in the database table. By defining a model, Django can automatically create the corresponding database table and handle database operations such as creating, updating, and deleting records.

## Migrations

Migrations are the way Django stores changes to your models (and thus your database schema) - they’re just files on disk. Migrations are designed to be run as a sequence, and to avoid conflicts and mistakes during development, we create them every time we make changes to our models. We’ll cover how to generate and apply migrations in the next blog.

## Set Up DB

By default, Django uses SQLite database, and hence we won’t change it for now. The first command that we need to run is :

```bash
python manage.py migrate
```

This command will create all the necessary tables in the database that Django uses to keep track of its own models. Once this command is run, you can create your own models and Django will automatically create the corresponding tables in the database.

After creating your models, you can use Django's Object-Relational Mapping (ORM) to interact with the database and perform various CRUD (Create, Read, Update, Delete) operations on the data.

Every time you change something in your model, you need to make the migrations again to make changes to the database tables.

For that, we can run the following commands to make migrations and apply changes to the db structure.

```bash
python manage.py makemigrations
python manage.py migrate

```

The first command `makemigrations` will create a new migration file in the migrations directory for every model that has changed. The second command `migrate` will apply those changes to the database. It's important to always run both commands in order to keep the database structure in sync with your models.

## Django ORM

Django ORM stands for Object-Relational Mapping. It is a powerful feature that allows us to interact with our database like we're working with Python objects. With the ORM, we can create, retrieve, update, and delete objects from the database using simple Python code. This makes working with databases in Django much easier and faster than writing SQL queries manually.

## Creating Models

In order to create models, we need to define a Python class that extends Django's `Model` class. Each attribute of the class represents a field in the database table. Django provides a variety of fields like `CharField`, `IntegerField`, `DateField`, `DateTimeField`, etc. that we can use to define our model's fields. We can also define relationships between models using fields like `ForeignKey`, `ManyToManyField`, and `OneToOneField`.

For eg. lets create a sample model for our `triviaquiz` app in `/quiz/models.py` file

```python
from django.db import models

class TriviaQuestion(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')
    answer = models.CharField(max_length=200)
    option1 = models.CharField(max_length=200)
    option2 = models.CharField(max_length=200)
    option3 = models.CharField(max_length=200)
    option4 = models.CharField(max_length=200)

		def __str__(self):
        return self.question_text
```

In this model, we have created a simple model for defining the attributes we want in the TriviaQuestion model. Do note the different kinds on fields we are using.

Now to use this, we need to add this model to our database.

To add the newly created model to the database, we need to create a migration for it. We can do this by running the following command in the terminal:

```bash
python manage.py makemigrations
```

This will create a new migration file , which includes the changes we made to the `TriviaQuestion` model. Next, we apply the migration using the following command:

```bash
python manage.py migrate
```

This will create the `triviaquestion` table in the database. Now to easily edit the data, we will also add this model in the `admin.py` file.

For example, let's say we want to display the TriviaQuestion model in the admin interface. We can create a custom admin class for this model in our `admin.py` file:

```python
from django.contrib import admin
from .models import TriviaQuestion

admin.site.register(TriviaQuestion)
```

This will display the question text and the date it was published in the admin interface for the TriviaQuestion model.

## Django Admin

Django Admin is a feature that comes with Django that allows us to easily manage our database data using a web interface. It is automatically generated based on the models we define in our app. To use it, we need to create a superuser first. We can do this by running the following command in the terminal:

```bash
python manage.py createsuperuser
```

This will prompt us to enter a username, email, and password for the superuser. Once we have created a superuser, we can access the admin interface by going to [`localhost:8000/admin`](http://localhost:8000/admin) in our browser and logging in with the superuser credentials.

In the next blog, we will dive deeper into how to use Django ORM to interact with the database and perform CRUD operations on the data. We will also discuss how to create custom admin classes and how to use the Django Admin interface to manage our database data more efficiently.