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

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

高洛峰
高洛峰Original
2016-12-27 14:54:311508browse

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.
    }
}

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()

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

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)

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',
)

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()

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:
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