How to set up the Database in Django?

Setting up a database in Django is a fairly straightforward process, and it can be done in just a few steps. In this tutorial, we will go through the process of setting up a database in Django using the built-in SQLite database engine.

Before we begin, make sure that you have Django installed on your system. If you don't have Django installed, you can install it using the following command:

pip install Django

 Once you have Django installed, let's create a new Django project using the following command:

django-admin startproject myproject

This will create a new directory called "myproject" which contains the basic files and directories needed for a Django project.

Next, we need to create a Django app within our project. We can do this using the following command:

python manage.py startapp myapp

This will create a new directory called "myapp" which contains the basic files and directories needed for a Django app.

Now that we have our Django project and app set up, we can start configuring the database. By default, Django uses the SQLite database engine, which is a lightweight, file-based database engine.

To set up the database, we first need to create a database model. A database model is a class that defines the fields and behaviors of the data that we want to store in the database.

For example, let's say we want to create a database model for storing information about books. Our model might look something like this:

from django.db import models

class Book(models.Model):
    title = models.CharField(max_length=200)
    author = models.CharField(max_length=200)
    publisher = models.CharField(max_length=200)
    publication_date = models.DateField()

This model has four fields: title, author, publisher, and publication_date. Each field is specified using a Django field type, such as CharField or DateField.

Once we have defined our model, we need to run a command to create the database tables for the model. To do this, we will use the migrate command:

python manage.py makemigrations
python manage.py migrate

The makemigrations command creates a migration file which specifies the changes that need to be made to the database. The migrate command applies these changes to the database.

Once the database is set up, we can start interacting with it using Django's ORM (Object-Relational Mapping) system. This allows us to query the database using Python code rather than SQL.

For example, to create a new book in the database, we can do the following:

from myapp.models import Book

book = Book(title='The Great Gatsby', author='F. Scott Fitzgerald',  
publisher='Charles Scribners Sons', publication_date='1925-04-10')
book.save()

 

This will create a new record in the book table of the database with the specified field values.

We can also query the database using the ORM. For example, to retrieve all books published by a particular publisher.

 

 

 

 

 

 

No comments

Powered by Blogger.