Home Backend Development Python Tutorial python Django connects to MySQL database for addition, deletion, modification and query

python Django connects to MySQL database for addition, deletion, modification and query

Dec 27, 2016 pm 02:54 PM

1. Download and install the MySQLdb class library
http://www.djangoproject.com/r/python-mysql/
2. Modify settings.py configuration data attributes

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'djangodb',                      # Or path to database file if using sqlite3.
        # The following settings are not used with sqlite3:
        'USER': 'root',
        'PASSWORD': 'root',
        'HOST': '127.0.0.1',                      # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
        'PORT': '3306',                      # Set to empty string for default.
    }
}
Copy after login

Modified Then enter DOS and enter the project directory to execute the python manage.py shell command to start the interactive interface and enter the code to verify whether the database configuration is successful. If no error is reported, it is successful!

>>> from django.db import connection
>>> cursor = connection.cursor()
Copy after login

3. Create a Django app
A project contains one or more such apps. An app can be understood as a collection of functions. For example, the product management module includes functions such as adding, deleting, and checking. Product management can be called an app. Each Django app has independent models, views, etc., which is easy to transplant and reuse.
DOS enters the project directory and executes python manage.py startapp products to generate the directory file as follows:

products/
    __init__.py
    models.py
    tests.py
    views.py
Copy after login

4. Write models

from django.db import models
# Create your models here.
class Company(models.Model):
    full_name = models.CharField(max_length=30)
    address = models.CharField(max_length=50)
    tel = models.CharField(max_length=15,blank=True)
class Product(models.Model):
    product_name = models.CharField(max_length=30)
    price = models.FloatField()
    stock = models.IntegerField(max_length=5)
    company = models.ForeignKey(Company)
Copy after login

5. Model installation (modify settings.py)

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # Uncomment the next line to enable the admin:
     'django.contrib.admin',
    # Uncomment the next line to enable admin documentation:
     'django.contrib.admindocs',
    'DjangoMysqlSite.products',
)
Copy after login

Use python manage.py validate to check whether the syntax and logic of the model are correct.
If there is no error, execute python manage.py syncdb to create the data table.
Now you can see that in addition to products_company and products_product, your database has also created several other tables. These are the tables required by the Django management background. Ignore them for now.

6. Simple addition, deletion, modification and query
Enter python manage.py shell

from DjangoMysqlSite.products.models import Company
>>> c = Company(full_name='集团',address='杭州西湖',tel=8889989)
>>> c.save()

>>> company_list = Company.objects.all()
>>> company_list

>>> c = Company.objects.get(full_name="集团")
>>> c.tel = 123456
>>> c.save()
 
>>> c = Company.objects.get(full_name="集团")
>>> c.delete()
#删除所有
>>> Company.objects.all().delete()
Copy after login

For more related articles about python Django connecting to MySQL database to perform addition, deletion, modification and query, please pay attention to the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the permissions problem encountered when viewing Python version in Linux terminal? How to solve the permissions problem encountered when viewing Python version in Linux terminal? Apr 01, 2025 pm 05:09 PM

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? Apr 01, 2025 pm 11:15 PM

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

How to dynamically create an object through a string and call its methods in Python? How to dynamically create an object through a string and call its methods in Python? Apr 01, 2025 pm 11:18 PM

In Python, how to dynamically create an object through a string and call its methods? This is a common programming requirement, especially if it needs to be configured or run...

How to teach computer novice programming basics in project and problem-driven methods within 10 hours? How to teach computer novice programming basics in project and problem-driven methods within 10 hours? Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How does Uvicorn continuously listen for HTTP requests without serving_forever()? How does Uvicorn continuously listen for HTTP requests without serving_forever()? Apr 01, 2025 pm 10:51 PM

How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

What are some popular Python libraries and their uses? What are some popular Python libraries and their uses? Mar 21, 2025 pm 06:46 PM

The article discusses popular Python libraries like NumPy, Pandas, Matplotlib, Scikit-learn, TensorFlow, Django, Flask, and Requests, detailing their uses in scientific computing, data analysis, visualization, machine learning, web development, and H

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

See all articles