0% found this document useful (0 votes)
8 views

Create-new-Database

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Create-new-Database

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

Create new Database

We can create the Database using the two ways - MySQL Workbench and
MySQL shell. MySQL Workbench is a GUI tool for the MySQL database that
provides features like SQL development, data modeling and server
administration. We will use the MySQL shell, which is more recommended for
learning purposes.

o Connect MySQL Server

o Create database using SQL queries

Use the create database my_database query. It will create the new
database.

We can check the databases through the show databases query.


1. mysql> show databases;

1. +--------------------------------------+
2. | Database |
3. +--------------------------------------+
4. | information_schema |
5. | my_database |
6. | mysql |
7. | performance_schema |
8. | sys |
9. +---------------------------------------+
10. 5 rows in set (0.05 sec)

It shows the all available database in our MySQL server.

Step - 3: Update the settings.py

Once we are done creating the Database, we have to update the database
section of the settings.py file with the following setting configuration.

1. DATABASES = {
2. 'default': {
3. 'ENGINE': 'django.db.backends.mysql',
4. 'NAME': 'my_database',
5. 'USER': 'root',
6. 'PASSWORD': 'your_password',
7. 'HOST': '127.0.0.1',
8. 'PORT': '3306',
9. 'OPTIONS': {
10. 'init_command': "SET sql_mode='STRICT_TRANS_TABLES'"
11. }
12. }
13. }

o First, we have replaced the 'django.db.backends.sqlite3' to


'django.db.backends.mysql'. This is basically indicating we shift SQLite
to MySQL database.
o NAME indicates the name of the database we want to use.
o USER is the MYSQL username that has access to the Database and
acts as a database administrator.
o PASSWORD is the password of the database. It will be created at the
time of MySQL installation.
o 'HOST' is '127.0.0.1' and 'PORT' '3306' points out that the MySQL
database is hosted with the hostname '0.0.1' and listens to the
specific port number is 3306.
o In the last line we use SET sql_mode =
'STATIC_TRANS_TABLES' which is used to handle the invalid or
missing values from being stored in the database by INSERT and
UPDATE statements.

Step - 4 Install mysqlclient package

Before installing the mysqlclient package, let's understand what mysqlclient


is and why we use. The mysqlclient is the Python interface to MySQL that
allows Python project to connect to the MySQL server.

So it is necessary to install mysqlclient package to establish the connection


between the MySQL and Django. To install, use the following command in the
working directory.

1. pip install mysqlclient

Step - 5 Run the migrate command

Now we are ready to migrate or create tables in the newly created database.
In this final step, we will run the migrate command and it will create the
exiting tables in the my_database database.

1. python manage.py migrate

After running this command Django will automatically create the necessary
tables such as auth_group, auth_user, auth_permission, etc. It will also
create the tables which are defined in the models.py file.

mysql> use my_database;

Database changed
mysql> show tables;

1. +-------------------------------------------------------+
2. | Tables_in_my_database |
3. +-------------------------------------------------------+
4. | auth_group |
5. | auth_group_permissions |
6. | auth_permission |
7. | auth_user |
8. | auth_user_groups |
9. | auth_user_user_permissions |
10. | django_admin_log |
11. | django_content_type |
12. | django_migrations |
13. | django_session |
14. | myweatherapp_profile |
15. +---------------------------------------------------------+
16. 11 rows in set (0.05 sec)

TO CREATE A SUPER USER ACCOUNT IN DJANGO

Django Admin Interface


Django provides a built-in admin module which can be used to perform CRUD
operations on the models. It reads metadata from the model to provide a
quick interface where the user can manage the content of the application.

This is a built-in module and designed to perform admin related tasks to the
user.

Let's see how to activate and use Django's admin module (interface).

The admin app (django.contrib.admin) is enabled by default and already


added into INSTALLED_APPS section of the settings file.

To access it at browser use '/admin/' at a local machine


like localhost:8000/admin/ and it shows the following output
winpty python manage.py createsuperuser.

Django Model
In Django, a model is a class which is used to contain essential fields and
methods. Each model class maps to a single table in the database.

Django Model is a subclass of django.db.models.Model and each field of


the model class represents a database field (column).

Django provides us a database-abstraction API which allows us to create,


retrieve, update and delete a record from the mapped table.

Model is defined in Models.py file. This file can contain multiple models.

Let's see an example here, we are creating a model Employee which has
two fields first_name and last_name.

1. from django.db import models


2.
3. class Employee(models.Model):
4. first_name = models.CharField(max_length=30)
5. last_name = models.CharField(max_length=30)

The first_name and last_name fields are specified as class attributes and
each attribute maps to a database column.

This model will create a table into the database that looks like below.

1. CREATE TABLE appname_employee (


2. "id" INT NOT NULL PRIMARY KEY,
3. "first_name" varchar(30) NOT NULL,
4. "last_name" varchar(30) NOT NULL
5. );

The created table contains an auto-created id field. The name of the table is
a combination of app name and model name that can be changed further.
Register / Use Model
After creating a model, register model into
the INSTALLED_APPS inside settings.py.

For example,

ADVERTISEMENT

1. INSTALLED_APPS = [
2. #...
3. 'appname',
4. #...
5. ]

Django Model Fields


The fields defined inside the Model class are the columns name of the
mapped table. The fields name should not be python reserve words like
clean, save or delete etc.

Django provides various built-in fields types.

Field Name Class Particular

AutoField class AutoField(**options) It An IntegerField that


automatically increments.

BigAutoField class BigAutoField(**options) It is a 64-bit integer, much


like an AutoField except that
it is guaranteed to fit
numbers from 1 to
9223372036854775807.

BigIntegerField class BigIntegerField(**options) It is a 64-bit integer, much


like an IntegerField except
that it is guaranteed to fit
numbers from -
9223372036854775808 to
9223372036854775807.
BinaryField class BinaryField(**options) A field to store raw binary
data.

BooleanField class BooleanField(**options) A true/false field. The default


form widget for this field is a
CheckboxInput.

CharField class DateField(auto_now=False, It is a date, represented in


auto_now_add=False, **options) Python by a datetime.date
instance.

DateTimeField class It is a date, represented in


DateTimeField(auto_now=False, Python by a datetime.date
auto_now_add=False, **options) instance.

DateTimeField class It is used for date and time,


DateTimeField(auto_now=False, represented in Python by a
auto_now_add=False, **options) datetime.datetime instance.

DecimalField class It is a fixed-precision decimal


DecimalField(max_digits=None, number, represented in
decimal_places=None, Python by a Decimal instance.
**options)

DurationField class DurationField(**options) A field for storing periods of


time.

EmailField class It is a CharField that checks


EmailField(max_length=254, that the value is a valid email
**options) address.

FileField class FileField(upload_to=None, It is a file-upload field.


max_length=100, **options)

FloatField class FloatField(**options) It is a floating-point number


represented in Python by a
float instance.

ImageField class It inherits all attributes and


ImageField(upload_to=None, methods from FileField, but
height_field=None, also validates that the
width_field=None, uploaded object is a valid
max_length=100, **options) image.

IntegerField class IntegerField(**options) It is an integer field. Values


from -2147483648 to
2147483647 are safe in all
databases supported by
Django.

NullBooleanField class NullBooleanField(**options) Like a BooleanField, but


allows NULL as one of the
options.

PositiveIntegerFi class Like an IntegerField, but must


eld PositiveIntegerField(**options) be either positive or zero (0).
Values from 0 to 2147483647
are safe in all databases
supported by Django.

SmallIntegerFiel class It is like an IntegerField, but


d SmallIntegerField(**options) only allows values under a
certain (database-dependent)
point.

TextField class TextField(**options) A large text field. The default


form widget for this field is a
Textarea.

TimeField class TimeField(auto_now=False, A time, represented in Python


auto_now_add=False, **options) by a datetime.time instance.

Django Model Fields Example


1. first_name = models.CharField(max_length=50) # for creating varchar column
2. release_date = models.DateField() # for creating date column
3. num_stars = models.IntegerField() # for creating integer column

Field Options
Each field requires some arguments that are used to set column attributes.
For example, CharField requires mac_length to specify varchar database.

Common arguments available to all field types. All are optional.


Field Particulars
Options

Null Django will store empty values as NULL in the database.

Blank It is used to allowed field to be blank.

Choices An iterable (e.g., a list or tuple) of 2-tuples to use as choices for this
field.

Default The default value for the field. This can be a value or a callable object.

help_text Extra "help" text to be displayed with the form widget. It's useful for
documentation even if your field isn't used on a form.

primary_key This field is the primary key for the model.

Unique This field must be unique throughout the table.

Django Model Example


We created a model Student that contains the following code
in models.py file.

//models.py

1. class Student(models.Model):
2. first_name = models.CharField(max_length=20)
3. last_name = models.CharField(max_length=30)
4. contact = models.IntegerField()
5. email = models.EmailField(max_length=50)
6. age = models.IntegerField()

After that apply migration by using the following command.

1. python3 manage.py makemigrations myapp

You might also like