YouTip LogoYouTip

Django Model

Django provides excellent support for various databases, including: PostgreSQL, MySQL, SQLite, and Oracle. Django provides a unified API for these databases. We can choose different databases based on our business needs. MySQL is the most commonly used database for web applications. In this chapter, we will use MySQL as an example for the introduction. You can learn more about the basics of MySQL through the (#) on this site. If you haven't installed the MySQL driver, you can execute the following command to install it: sudo pip3 install pymysql ## Django ORM Django models use the built-in ORM. Object-Relational Mapping (ORM) is used to implement the conversion of data between different type systems in object-oriented programming languages. ORM acts as a bridge between the business logic layer and the database layer. ORM automatically persists objects in the program to the database by using metadata that describes the mapping between objects and the database. !(#) Advantages of using ORM: * Improves development efficiency. * Allows for smooth switching between different databases. Disadvantages of using ORM: * Converting ORM code to SQL statements takes some time, which reduces execution efficiency. * Writing ORM code for a long time can reduce the ability to write SQL statements. ORM parsing process: * 1. ORM converts Python code into SQL statements. * 2. SQL statements are sent to the database server via pymysql. * 3. SQL statements are executed in the database, and the results are returned. ORM correspondence table: !(#) * * * ## Database Configuration ### How Django Uses MySQL Database To create a MySQL database (ORM cannot operate at the database level, only at the table level), the syntax is: create database database_name default charset=utf8; # Prevent encoding issues by specifying utf8 For example, we create a database named tutorial with utf8 encoding: create database tutorial default charset=utf8; We find the DATABASES configuration item in the project's settings.py file and modify its information to: ## HelloWorld/HelloWorld/settings.py: File Code: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'tutorial', 'HOST': '127.0.0.1', 'PORT': 3306, 'USER': 'root', 'PASSWORD': '123456', } } If you are using Python 2.x and have added Chinese comments, you need to add `# -*- coding: UTF-8 -*-` at the top of the HelloWorld/settings.py file. The above includes the database name and user information, which correspond to the settings for the database and user in MySQL. Django uses this configuration to connect to the corresponding database and user in MySQL. Next, tell Django to use the pymysql module to connect to the MySQL database: ## Example # Import the module and configure it in the __init__.py file at the same level as settings.py import pymysql pymysql.install_as_MySQLdb() * * * ## Defining Models ### Creating an APP Django requires that if you want to use models, you must create an app. We use the following command to create an app named TestModel: django-admin startapp TestModel The directory structure is as follows: HelloWorld|-- HelloWorld|-- manage.py ...|-- 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: from django.db import models class Test(models.Model): name = models.CharField(max_length=20) The class name above represents the database table name and inherits from models.Model. The fields inside the class represent the fields in the data table (name), and the data type is determined by CharField (equivalent to varchar), DateField (equivalent to datetime), with the max_length parameter specifying the length. Next, find the INSTALLED_APPS item in settings.py, as shown below: INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'TestModel', # Add this item) Run the following commands in the command line: $ python3 manage.py migrate # Create table structure $ python3 manage.py makemigrations TestModel # Let Django know we have made some changes to our models $ python3 manage.py migrate TestModel # Create table structure You will see several lines of "Creating table…" indicating that your data table has been created. Creating tables ...……Creating table TestModel_test # Our custom table…… The table name structure is: app_name_class_name (e.g., TestModel_test). **Note:** Although we did not set a primary key for the table in the models, Django will automatically add an id as the primary key. ### Common Error Messages If you encounter the following error message when executing the above commands: !(#) The reason is that MySQLclient currently only supports up to Python 3.4. Therefore, if you are using a higher version of Python, you need to modify it as follows: Find the base.py file in the path ...site-packagesDjango-2.0-py3.6.eggdjangodbbackendsmysql from the error message's file path, and comment out these two lines of code (the code is at the beginning of the file): if version < (1, 3, 13): raise ImproperlyConfigured('mysqlclient 1.3.13 or newer is required; you have %s.' % Database. __version__ ) !(#) Generally, clicking the error's code file path information will automatically jump to the line number in the error file. At this point, we comment out the code at the error line number. If you encounter the following error message: !(#) We click the error's code file path to jump to the line number in the error file. At this point, we add the following before the error line number: query = query.encode() !(#) * * * ## Database Operations Next, we add a testdb.py file (introduced below) in the HelloWorld directory and modify urls.py: ## HelloWorld/HelloWorld/urls.py: File Code: from django.urls import path from . import views,testdb urlpatterns = [path('tutorial/', views.tutorial), path('testdb/', testdb.testdb), ] ### Adding Data To add data, you first need to create an object and then execute the save function, which is equivalent to INSERT in SQL: ## HelloWorld/HelloWorld/testdb.py: File Code: from django.http import HttpResponse from TestModel.models import Test def testdb(request): test1 = Test(name='tutorial')test1.save()return HttpResponse("

Data added successfully!

") Visit **http://127.0.0.1:8000/testdb** to see the prompt indicating that the data was added successfully. The output is as follows: !(#) ### Retrieving Data Django provides multiple ways to retrieve database content, 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 = ""listTest = Test.objects.all()response2 = Test.objects.filter(id=1)response3 = Test.objects.get(id=1)Test.objects.order_by('name')[0:2]Test.objects.order_by("id")Test.objects.filter(name="tutorial").order_by("id")for var in listTest: response1 += var.name + ""response = response1 return HttpResponse("

" + response + "

") ### Updating Data To modify data, you can use save() or update(): ## HelloWorld/HelloWorld/testdb.py: File Code: from django.http import HttpResponse from TestModel.models import Test def testdb(request): test1 = Test.objects.get(id=1)test1.name = 'Google'test1.save()return HttpResponse("

Modification successful

") ### Deleting Data To delete an object from the database, simply call the object's delete() method: ## HelloWorld/HelloWorld/testdb.py: File Code: from django.http import HttpResponse from TestModel.models import Test def testdb(request): test1 = Test.objects.get(id=1)test1.delete()return HttpResponse("

Deletion successful

")
← Md AdvanceMd Image β†’