Introduce : In this lesson, we continue to learn djangoWEB Development of framework , This lesson is mainly about how to access the database ,django How to automatically create a good table structure and other related content for us .
1、 First let's open up settings.py find DATABASES keyword , This is to configure our database .
The attributes inside are not introduced , I can understand it at a glance .
2、 Add one of your own startapp polls, And in settings Middle configuration .
You can also write directly 'polls'
3、 Open the app we just created polls -->models.py The contents are as follows :
# -*- coding: utf-8 -*-
from __future__ import unicode_literals from django.db import models # Create your models here. class Test(models.Model): name = models.CharField(max_length=20) explain :
The above class name represents the database table name , And inherited models.Model, The fields in the class represent the fields in the data table (name),
The data type is determined by CharField( amount to varchar)、DateField( amount to datetime), max_length Parameter limit length .
4、 stay pycharm Run in manage.py
After success :
We carry out three orders as follows :
# Create a table structure ( Built in django Table structure )
[email protected] > migrate
D:\PyCharm\bin\runnerw.exe D:\Python\python.exe D:\PyCharm\helpers\pycharm\django_manage.py migrate D:/pythondjango
Operations to perform:
Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying admin.0002_logentry_remove_auto_add... OK
Applying contenttypes.0002_remove_content_type_name... OK
Applying auth.0002_alter_permission_name_max_length... OK
Applying auth.0003_alter_user_email_max_length... OK
Applying auth.0004_alter_user_username_opts... OK
Applying auth.0005_alter_user_last_login_null... OK
Applying auth.0006_require_contenttypes_0002... OK
Applying auth.0007_alter_validators_add_error_messages... OK
Applying auth.0008_alter_user_username_max_length... OK
Applying sessions.0001_initial... OK
Process finished with exit code 0
Give Way Django Know we have some changes in our model , Generate a file
[email protected] > makemigrations polls
D:\PyCharm\bin\runnerw.exe D:\Python\python.exe D:\PyCharm\helpers\pycharm\django_manage.py makemigrations polls D:/pythondjango
Migrations for 'polls':
polls\migrations\0001_initial.py
- Create model Test
Following files were affected
D:\pythondjango\polls\migrations\0001_initial.py
Process finished with exit code 0
The content of the document is :
# -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-07-21 09:15
from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [
] operations = [
migrations.CreateModel(
name='Test',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=20)),
],
),
] In fact, it records some changes in the database
[email protected] > migrate polls
D:\PyCharm\bin\runnerw.exe D:\Python\python.exe D:\PyCharm\helpers\pycharm\django_manage.py migrate polls D:/pythondjango
Operations to perform:
Apply all migrations: polls
Running migrations:
Applying polls.0001_initial... OK
Process finished with exit code 0
The table name structure is : Application name _ Class name
Be careful : Although we are not in models Set the primary key for the table , however Django Will automatically add a id A primary key .
Operating the database :
stay urls.py Add a map to :
Add a value to the database , modify views.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.http import HttpResponse from polls.models import Test
from django.shortcuts import render # Create your views here. # Database operation
def testdb(request):
test1 = Test(name=' Wen Hongyu ')
test1.save()
return HttpResponse("<p> Data added successfully !</p>") Add success :
summary : This lesson mainly shares django And mysql The collocation of database , How to create a database table structure ,settings Configure the database in the file , Add your own new app , How to be in models.py Create an instance in , The meaning of the attribute, etc Rong . At the same time with the help of pycharm Automatically generate database tables , And creating a table structure doesn't need to specify a primary key ,django Will help us create a id. stay views.py To add a value to a database in .
django MVC Pattern Operation of database mysql More articles about
- mysql database ----python operation mysql ------pymysql and SQLAchemy
This article is about Python operation MySQL There are two main ways : native module pymsql ORM frame SQLAchemy One .pymysql pymsql yes Python In the operation MySQL Module , How to use it and MySQ ...
- java database JDBC operation MySQL Databases are commonly used API Department tables and staff tables Create table Add data Query data
package com.swift.department; import java.sql.Connection; import java.sql.PreparedStatement; import ...
- Flask Learning notes : database ORM operation MySQL+pymysql/mysql-python+SQLAlchemy/Flask-SQLAlchemy
Python Use in sqlalchemy Plugins can implement ORM(Object Relationship Mapping, Model relation mapping ) frame , and Flask Medium flask-sqlalchemy In fact, in the sqla ...
- MySQL database 4Python operation mysql、 Indexes 、 Slow query log
Catalog One .Python operation mysql 1.1python operation mysql 1.2 Query data 1.3 increase ( add to . to update ) data 1.4 Modifying data 1.5 Delete data 1.6SQL Injection problem 1.6.1 The introduction of questions ...
- database -python operation mysql(pymsql)
pymsql yes Python In the operation MySQL Module , How to use it and MySQLdb Almost the same One : install pymysql pip3 install pymysql Two : Use pytmysql # -*- codin ...
- JDBC Database common operations (mysql)
JDBC English name :JavaDataBaseConnectivity Chinese name :java Database connection is short for :JDBCJDBC It's one for execution SQL Of the statement JavaAPI, It can provide unified access for a variety of relational databases , It consists of a group of ...
- python operation mysql Database Series - operation MySql database ( Two )
Interface test framework hierarchical directory structure diagram : page Under directory mysqlTest.py: Deposit is mysql Operation code of utils Under directory helper.py: It stores public configuration methods log Catalog log.md: Deposit ...
- Database common operations (mysql)
establish create database Library name create table Table name ( Name type(varchar(size),int(size),decimal(size,d))) "size&q ...
- scrapy It's used in pipes mysql Insert database python operation mysql
# -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to t ...
Random recommendation
- HashBytes(Transact-SQL)
Returns the MD2.MD4.MD5.SHA or SHA1 Hash value grammar HashBytes('<algorithm>',{@input|'input'}) <algorithm>:: ...
- Kali linux Summary of common penetration testing tools 2- Penetration attack
The idea of penetration attack is to scan vulnerabilities , And then exploit different vulnerabilities , Only then has the targeted penetration attack . Vulnerability scanning tools include Nessus, The tool can be remotely controlled locally or remotely at the same time , Analysis and scanning of system vulnerabilities .Nessus By creating a new scan strategy , And add the corresponding plug-in ...
- Janus WinForms Controls
http://blog.sina.com.cn/s/blog_68eb92020101kpw8.html
- Python for loop invalid
Yesterday, we found that a base class responsible for handling the observer pattern failed , default N An observer is responsible for handling Something sent , It provides a built-in interface to remove the observer : def removeObserver(self, observer): if ...
- usb Key mouse drive analysis
One . mouse linux Under the usb Mouse driven in /drivers/hid/usbhid/usbmouse.c To realize 1. Load initialization process 1.1 Module entry module_init(usb_mouse_init); ...
- Redis Summary of cache related issues
Using caching is the first golden rule of system performance optimization . The design and use of cache is very important to the performance of a system , No matter how many items you contact, you will also use caching at some levels , For example, use HashMap Realization ,Ehcache,memcached.redi ...
- WPF rewrite ListBox( Transparent effect )
<UserControl d:DesignHeight="460" d:DesignWidth="300" x:Name="UCcontrol& ...
- Linux In the environment Scala Environment building
1. download tag After the package , I'm used to putting software Under the folder , And establish app Folder 2. adopt tar -zxvf scala-2.12.8.tgz -C ~/app/ Unzip the command to app Under the table of contents (-C Is the specified directory ...
- [ turn ] look out PHP Class definition order and inheritance
FROM : http://www.pakey.net/blog/php-class-shunxu.html The running environment of the following code is PHP5.3.11 Let's start with a piece of code <?php class A ...
- 【Android Development 】 And MediaPlayer Error analysis of
I've been working on a media player recently , Used Android Self contained MediaPlayer, It happens all the time MediaPlayer An error report , I've looked online for , I feel that the summary is not very good or scattered . below , Let me summarize the use of MediaPlaye ...