Django (iii) ORM database operations

Source: Internet
Author: User
Tags sqlite

More useful

Transfer from http://blog.csdn.net/fgf00/article/details/53678205

First, djangoorm create basic types and build database table structure
1. Introduction
2. Create DATABASE table structure
Second, Django ORM Basic additions and deletions to change
1, table data additions and deletions to check
2. Table Structure Modification
Third, Django ORM field type
1. Description of field type
2. Description of field parameters
3. Django ORM FOREIGN key operation

First, djangoorm create basic types and build database table structure

1. Introduction

ORM: Relational object mapping. Defines a table structure in which a class automatically generates a database.

When you create a database, you typically have the following common data types: numbers, strings, and time.

ORM is divided into two types:

DB first database to create a database table structure, according to the table structure to generate classes, according to the class operation database
Code first writes codes, executes code to create database table structure
The mainstream ORM is code first. Django's ORM is also code first, so when you learn it, it's essentially divided into two pieces:

To automatically create a database table from a class
Perform various operations on data in a database table based on a class
2. Create DATABASE table structure

Write First class:
App models.py file:

From django.db import Models

Class UserInfo (models. Model): # must inherit models. Model
# without writing then, django default create ID column, auto increment, primary key
# user list, string type, specified length
Username = models. Charfield (MAX_LENGTH=32)
Password = models. Charfield (max_length=64)

Register app
Executing the command Python manage.py makemigrations will prompt no changes detected because all models are found when executing the command, but Django does not know which one to look for and all it needs to specify.

settings.py,

Installed_apps = [
' Django.contrib.admin ',
' Django.contrib.auth ',
' Django.contrib.contenttypes ',
' Django.contrib.sessions ',
' Django.contrib.messages ',
' Django.contrib.staticfiles ',
' App01 ', # Add app here
]

Executing a command-generation table structure
Python manage.py makemigrations # generate migrations Temporary files
Python manage.py Migrate # Direct database generation based on migrations
1
2
After execution, the operation record is generated from migrations. Build the database, using the Sqlite3 by default. Can be opened directly with software such as Navicat.

Db.sqlite3 contains cache, session, cookie, static file, and background management. Like we created a table called: App01_userinfo

Connect to MySQL Database
If you are not using SQLite, use the MySQL database. The code does not change, the command does not change, only need to change the configuration file.

# https://docs.djangoproject.com/en/1.10/ref/settings/#databases Official documents
# DATABASES = {# sqlite default
# ' default ': {
# ' ENGINE ': ' Django.db.backends.sqlite3 ',
# ' NAME ': Os.path.join (Base_dir, ' db.sqlite3 '),
# }
# }
DATABASES = {# MySQL
' Default ': {
' ENGINE ': ' Django.db.backends.mysql ',
' NAME ': ' MyDatabase ',
' USER ': ' Mydatabaseuser ',
' PASSWORD ': ' MyPassword ',
' HOST ': ' 127.0.0.1 ',
' PORT ': ' 3306 ',
}
}

Attention:

Database name Django cannot be created and needs to be created in advance

Django uses the MySQLdb module to link mysql by default, but Python3 now has no mysqldb, so instead use Pymysql to connect. Within the project name __init__.py

Import Pymysql
Pymysql.install_as_mysqldb ()
1
2
Second, Django ORM Basic additions and deletions to change

1, table data additions and deletions to check

urls.py

URL (r ' ^orm/', views.orm),
1
app01/views.py

From APP01 import models # importing models modules
def ORM (Request):
# Create Data
# The first way
# models. UserInfo.objects.create (username= "root", password= "123")
# The second way
# obj = models. UserInfo (username= ' Fzh ', password= "Iajtag")
# Obj.save ()
# The Third Way
# dic = {' username ': ' FGF ', ' Password ': ' 666 '}
# models. UserInfo.objects.create (**dic)

# Querying data
# result = models. UserInfo.objects.all () # Query all, for the Queryset type, can be understood as a list
# result = models. UserInfo.objects.filter (username= "FGF", password= "666") # List
# result = models. UserInfo.objects.filter (username= "FGF"). First () # object
# conditional Query. The filter is equivalent to the where query condition, where the "," will form an and condition
# for row in result: # Print query to data.
# Print (Row.id,row.username,row.password)

# view Queryset type specifically what to do, can: print (result.query)

# Delete Data
# models. UserInfo.objects.all (). Delete () # Remove All
# models. UserInfo.objects.filter (id=4). Delete () # deletes all

# Update Data
# models. UserInfo.objects.all (). Update (password=8888)
# models. UserInfo.objects.filter (id=3). Update (password=888888)

Return HttpResponse (' ORM ')

2. Table Structure Modification

modifying columns
Password The field in the originally defined class = models. Charfield (max_length=64) changed to Password = models. Charfield (max_length=60). Once the Python manage.py makemigrations,python manage.py migrate is re-executed, the data table structure has changed. If the content in the column exceeds the defined size, the data is lost.

Add a column
Add a column to the class, execute the command, and the message will be prompted because it is not allowed to be empty by default. There are two options available.

Enter a value that adds the rows that already exist by default plus the input content.
email = models. Charfield (max_length=32, null=true), allowed to be empty
When you look at the table structure changes, the refresh does not appear and you need to reopen the table to see the effect.

Delete Column
Delete the corresponding field within the class and execute the command.

Third, Django ORM field type

1. Description of field type

In the Django ORM field type, there are Charfield, Emailfield, Urlfield, Genericipaddressfield, and so on, which are actually strings in the database. Can't do check grammar, can't do verification. What's the use of that?

These are for the Django Admin. Do the validation on the admin page. If you don't use admin, those are strings, the effect is the same.

Custom self-increment column: models. Autofield (Primary_key=true)

1, models. Autofield self-increment = Int (11)
If not, the default is to generate a column named ID, and if you want to display a custom self-increment column, you must set the column as the primary key primary_key=true.
2, models. Charfield string Field
Parameters must be max_length
3, models. Booleanfield Boolean type =tinyint (1)
Cannot be empty, blank=true
4, Models.comaseparatedintegerfield with comma-separated digital =varchar
Inherit Charfield, so the parameter must be max_lenght
5, models. Datefield Date Type Dates
For parameters, Auto_now = True updates the time for each update, and Auto_now_add only creates the addition for the first time, and subsequent updates no longer change.
6, models. Datetimefield Date Type DateTime
Parameters of the same Datefield
7, models. Decimal decimal Fractional type = Decimal
Integer digits max_digits and decimal digits must be specified decimal_places
8, models. Emailfield String type (regular expression mailbox) =varchar
To make a regular expression on a string
9, models. Floatfield floating-point type = Double
10, models. Integerfield Plastic Surgery
11, models. Bigintegerfield Long Plastic
Integer_field_ranges = {
' Smallintegerfield ': (-32768, 32767),
' Integerfield ': (-2147483648, 2147483647),
' Bigintegerfield ': (-9223372036854775808, 9223372036854775807),
' Positivesmallintegerfield ': (0, 32767),
' Positiveintegerfield ': (0, 2147483647),
}
12, models. Ipaddressfield String type (IP4 regular expression) (deprecated, with 13,)
13, models. Genericipaddressfield String Types (IP4 and IP6 are optional)
Parameter protocol can be: both, IPv4, IPv6
When verifying, the error is set according to the setting
14, models. Nullbooleanfield Boolean type allowed for null
15, models. Positiveintegerfiel positive integer
16, models. Positivesmallintegerfield Zheng Smallinteger
17, models. Slugfield minus, underline, letter, number
18, models. Smallintegerfield Digital
The fields in the database are: tinyint, smallint, int, bigint
19, models. TextField string =longtext
20, models. Timefield time Hh:mm[:ss[.uuuuuu]]
21, models. Urlfield string, address regular expression
22, models. Binaryfield binary
23, models. ImageField Pictures
24, models. Filepathfield file

As so many fields, can be roughly divided into string, number, time, binary, self-increment (primary_key=true) several categories.

2. Description of field parameters

field parameters in the database
NULL # Whether it can be empty
Default # Defaults
Primary_key # PRIMARY Key
Db_column # Column Name
Db_index # Index (db_index=true)
Unique # Single index (unique=true)
Unique_for_date # index only on dates
Unique_for_month # Index only on month
Unique_for_year # Index only for years
Auto_now # when created, automatically generate time
Auto_now_add # Update is automatically updated to the current time

# Update time does not support this
obj = UserGroup.objects.filter (id=1). Update (caption= ' CEO ')
obj = UserGroup.objects.filter (id=1). First () # Auto update time needs to be written like this
Obj.caption = "CEO"
Obj.save ()

The following are the field parameters for admin only
Choices # Function: 1, Django admin display drop-down box; 2. Avoid the list query
1
user_type_choices = (# database only 1, 2, 3, the following information exists in memory.
(1, ' Super user '),
(2, ' normal user '),
(3, ' General user '),
)
USER_TYPE_ID = models. Integerfield (Choices=user_type_choices,default=1)

Blank # Whether the Django Admin can be empty
Verbose_name # Django admin display field Chinese
Editable # Whether Django admin can be edited
Error_messages # error message
# error_messages={"required": "Password cannot be empty",} # Note must have comma
Help_text # Django Admin Tips
Validators # Django form, custom error message

Python manage.py createsuperuser # Create a Django user

3. Django ORM FOREIGN key operation

One-to-many relationships, models. ForeignKey (Colordic)

models.py

Table Association
Class UserGroup (models. Model):
UID = models. Autofield (Primary_key=true)
Caption = models. Charfield (Max_length=32,unique=true)
CTime = models. Datetimefield (Auto_now_add=true, Null=true)
Uptime = models. Datetimefield (Auto_now=true, Null=true)

Class UserInfo (models. Model):
Username = models. Charfield (max_length=32,blank=true,verbose_name= ' username ')
Password = models. Charfield (max_length=60, help_text= ' pwd ')
email = models. Charfield (max_length=60)
Test = models. Emailfield (max_length=19,null=true,error_messages={' invalid ': ' Please enter password ',})
# UserInfo table does not have user_group field, but user_group_id column value is UID number
User_group = models. ForeignKey ("UserGroup", to_field= ' uid ') # FOREIGN Key Association **********

Data query
User_list = Userinfo.objects.all () # Gets the Userinfo object
For row in User_list: #
Print (row.user_group_id) # Real data in the database
# User_group: Refers to the UserGroup object. Class UserGroup objects are encapsulated (uid,catption,ctime,uptime)
Print (ROW.USER_GROUP.UID) # Get UID from object, same as user_group_id
Print (row.user_group.caption) # Get caption through objects

Create data
UserInfo table Create data, how to write it?

Models. UserInfo.objects.create (
Username= ' Root1 ',
Password= ' 123 ',
Email= "Asdfasdf",
Test= "Asdfasdf",
# The first way: querying the database again, not recommended
# User_group = models. UserGroup.objects.filter (id=1). First ()
# The second way: Through the foreign key field _id
user_group_id = 1
)

Django (iii) ORM database operations

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.