DEV Community

Cover image for Django model
toebes618
toebes618

Posted on

Django model

Django supports a variety of databases, including PostgreSQL, MySQL, SQLite, Oracle.

Django provides a unified call API for these databases. We can choose different databases based on our own business needs.

MySQL is the most commonly used database in web applications. We'll cover Mysql as an example in this section. You can learn more about the basics of Mysql in this site.

If you don't have mysql driver installed, you can perform the following command installation:

sudo pip install mysqlclient

If you are new to Django, this is a good Django course

Database configuration

We set the DATABASES configuration in the project's settings.py file and changed its information to:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'test',
        'USER': 'test',
        'PASSWORD': '****yourpassword****',
        'HOST':'localhost',
        'PORT':'3306',
    }
}

It contains database names and user information, which are the same as the corresponding database and user settings in MySQL. Based on this setting, Django connects to the appropriate databases and users in MySQL.

Defining a model

Django states that if you want to use a model, you must create an app. We use the following command to create an app for TestModel:

python manage.py startapp TestModel

The directory structure is as follows:

HelloWorld
|-- TestModel
|   |-- __init__.py
|   |-- admin.py
|   |-- models.py
|   |-- tests.py
|   `-- views.py

We modify the TestModel/models.py file with the following code:

HelloWorld/TestModel/models.py: file code:

# models.py
from django.db import models

class Test(models.Model):
    name = models.CharField(max_length=20)

The above classes represent the database name and inherit models. Model, the fields inside the class represent the fields in the data table (name), and the data types are defined by CharField (equivalent to varchar) and the max_length parameters.

Next, find this INSTALLED_APPS in settings.py, as follows:

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'TestModel',
)

Run on the command line:

Note: In Django 1.9 and future versions use migrate instead of syscdb.

$ python manage.py migrate
$ python manage.py makemigrations TestModel
$ python manage.py migrate TestModel

You'll be able to create your data sheet with a few lines of the words "Creative table...".

Creating tables ...
…… 
Creating table TestModel_test
……

The table name is composed of: app name, class name (e.g., TestModel_test).

Note: Although we didn't set the primary key to the table in models, Django automatically adds an id as the primary key.

Database operations

Next, we add testdb.py files in the HelloWorld directory and modify urls.py:

from django.conf.urls import *
from HelloWorld.view import hello
from HelloWorld.testdb import testdb

urlpatterns = patterns("",
        ('^hello/$', hello),
        ('^testdb/$', testdb),
)

Add data

Adding data requires creating an object before executing the save function, which is equivalent to INSERT in SQL:

from django.http import HttpResponse
from TestModel.models import Test

def testdb(request):
  test1 = Test(name='dev.to')
  test1.save()
  return HttpResponse("<p>saved</p>")

Visit /testdb/ you can see a hint of success in adding data. If you want you can verify this in the MySQL database table.

Get data

Django provides a variety of ways to get the contents of the database, as shown in the following code:

HelloWorld/HelloWorld/testdb.py: File code:

from django.http import HttpResponse
from TestModel.models import Test

def testdb(request):
    response = ""
    response1 = ""

    # Get all the data the all() method, this is equivalent to SELECT * in SQL.  
    list = Test.objects.all()

    # Filter is equivalent to WHERE in SQL
    response2 = Test.objects.filter(id=1) 

    # Get a single object
    response3 = Test.objects.get(id=1) 

    # Limit returned data equivalent to OFFSET 0 LIMIT 2 in SQL
    Test.objects.order_by('name')[0:2]
    Test.objects.order_by("id")
    Test.objects.filter(name="dev.to").order_by("id")

    # Output all data
    for var in list:
        response1 += var.name + " "

    response = response1
    return HttpResponse("<p>" + response + "</p>")

Update data

Modifying data can be made using save() or update():

HelloWorld/HelloWorld/testdb.py: File code:

from django.http import HttpResponse

from TestModel.models import Test

def testdb(request):
    # equivalent to UPDATE in SQL
    test1 = Test.objects.get(id=1)
    test1.name = 'dev.to'
    test1.save()

    # Another way
    #Test.objects.filter(id=1).update(name='dev.to')

    # Modify all columns
    # Test.objects.all().update(name='dev.to')

    return HttpResponse("<p>Updated</p>")

Delete data

Simply call the delete() method of the object in the database by deleting it:

HelloWorld/HelloWorld/testdb.py: File code:

from django.http import HttpResponse

from TestModel.models import Test

def testdb(request):
    # Delete data where id=1
    test1 = Test.objects.get(id=1)
    test1.delete()

    # Another way
    # Test.objects.filter(id=1).delete()

    # Delete all data
    # Test.objects.all().delete()

    return HttpResponse("<p>Deleted</p>")

Top comments (0)