Python Django connects to the MySQL database to add delete and update

  • 2020-04-02 13:13:51
  • OfStack

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


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

After the modification, enter DOS into the project directory and execute the python manage.py shell command to launch the interactive interface. Enter the code to verify whether the database configuration is successful. No error is success!

>>> from django.db import connection
>>> cursor = connection.cursor()

  3. Create a Django app
A project contains one or more of these apps. App can be understood as a collection of functions. For example, the product management module contains such functions as adding, deleting and checking, and product management can be called an app. Each Django app has independent models, views, etc., which are easy to port and reuse.
DOS goes into 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 that the syntax and logic of the model is correct.
If there are no errors, the python manage.py syncdb is executed to create the data table.
Now you can see that your database has created several other tables in addition to products_company and products_product, which are the required tables for django administration.

6, simply add, delete, change and check
  Go to the python manage.py shell

from DjangoMysqlSite.products.models import Company
>>> c = Company(full_name=' group ',address=' Hangzhou west lake ',tel=8889989)
>>> c.save()

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

>>> c = Company.objects.get(full_name=" group ")
>>> c.tel = 123456
>>> c.save()
 
>>> c = Company.objects.get(full_name=" group ")
>>> c.delete()
# Delete all 
>>> Company.objects.all().delete()


Related articles: