Django Getting Started 4:orm database operations

Source: Internet
Author: User
Tags sqlite

Outline

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:

1  from Import Models 2 3 class UserInfo (models. Model):  #  must inherit models. Model4     #  does not write, django default create ID column, self increment, primary key 5     #  The User Name column, string type, specifying the length 6     username = models. Charfield (max_length=32)7     password = models. Charfield (max_length=64)
View Code
    • Register app

Executing python manage.py makemigrations the command prompts No changes detected you 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:

1Installed_apps = [2     'Django.contrib.admin',3     'Django.contrib.auth',4     'Django.contrib.contenttypes',5     'django.contrib.sessions',6     'django.contrib.messages',7     'Django.contrib.staticfiles',8     'APP01',#Add app here9]
View Code
    • Executing a command-generation table structure

1 python manage.py makemigrations # Generate migrations Temp file

2 python manage.py migrate # Direct Database generation based on migrations     

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. The table we created was 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.

1 #https://docs.djangoproject.com/en/1.10/ref/settings/#databases Official documents2 #DATABASES = {# sqlite default3 #' default ': {4 #' ENGINE ': ' Django.db.backends.sqlite3 ',5 #' NAME ': Os.path.join (Base_dir, ' db.sqlite3 '),6 #     }7 # }8DATABASES = {#MySQL9     'default': {Ten         'ENGINE':'Django.db.backends.mysql', One         'NAME':'MyDatabase', A         'USER':'Mydatabaseuser', -         'PASSWORD':'MyPassword', -         'HOST':'127.0.0.1', the         'PORT':'3306', -     } -}
View Code

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 pymysqlpymysql.install_as_MySQLdb()
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  fromApp01ImportModels#Import Models Module2 defORM (Request):3 #Create Data4     #The first way5     #models. UserInfo.objects.create (username= "root", password= "123")6     #The second way7     #obj = models. UserInfo (username= ' Fzh ', password= "Iajtag")8     #Obj.save ()9     #The Third WayTen     #dic = {' username ': ' FGF ', ' Password ': ' 666 '} One     #models. UserInfo.objects.create (**dic) A  - #Querying Data -     #result = models. UserInfo.objects.all () # Query all, for the Queryset type, can be understood as a list the     #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: # Prints the query to the data.  +     #print (Row.id,row.username,row.password) -  +     #See Queryset types specifically what to do, can: print (result.query) A  at #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) in     #models. UserInfo.objects.filter (id=3). Update (password=888888) -  to     returnHttpResponse ('ORM')
app01/views.py 2. Table Structure Modification
    • modifying columns

Change the field in the originally defined class to password = models.CharField(max_length=64) password = models.CharField(max_length=60) . Re-executed, the python manage.py makemigrations python manage.py migrate 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.

    1. Enter a value that adds the rows that already exist by default plus the input content.
    2. 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 columns :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. The Charfield string field must be max_length parameter 3, models. Booleanfield Boolean type =tinyint (1) cannot be empty, blank=true4, models. Comaseparatedintegerfield a comma-separated number =varchar inherits Charfield, so the parameter 5, models must be max_lenght. Datefield Date type dates for parameters, Auto_now = True, the time is updated for each update, and Auto_now_add is only the first time that the update is created, and then the updates are no longer changed. 6, models. Datetimefield Date type datetime with Datefield parameter 7, models. Decimal decimal Decimal type = decimal must specify integer digits max_digits and decimal places DECIMAL_PLACES8, models. Emailfield String type (regular expression mailbox) =varchar Regular Expression 9, models for strings. Floatfield floating-point type = Double10, models. Integerfield Plastic 11, models. Bigintegerfield Long Plastic integer_field_ranges = {' Smallintegerfield ': ( -32768, 32767), ' Integerfield ': (-2147483648, 2     147483647), ' 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) parameters protocol can be: both, IPv4, IPv6 validation, according to the set error 14, models. Nullbooleanfield is allowed to be null for Boolean type 15, models. Positiveintegerfiel is Integer16, models. Positivesmallintegerfield is SmallInteger17, models. Slugfield minus, underscore, letter, number 18, models. The fields in the Smallintegerfield digital database are: tinyint, smallint, int, bigint19, models. TextField string =longtext20, 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                # can be empty             default # defaults # Primary_key         # PRIMARY key db_column           # column name Db_index            # index (db_index=true) Unique              # Unique index (unique=true) Unique_for_date # only for the     date index Unique_for_month    # Only for the month index Unique_for_year     # Index only to year Auto_now            # when created, auto-generated time auto_now_add        # Update automatically updates 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 ()  # Automatic Update time needs to be written        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
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              # Django Admin can be empty verbose_name       # Django admin display field Chinese editable           # Django admin can be edited error_messages     # error message    # error_messages={"required": "Password cannot be empty",}  # Note must have comma Help_text          # Django admin prompt 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 has no user_group field, but User_ The group_id column value is the UID number    User_group = models. ForeignKey ("UserGroup", to_field= ' uid ')      # Foreign Key Association **********

  

    • Data query
User_list = Userinfo.objects.all ()  # gets Userinfo object for row in user_list:               #     print (row.user_group_id)        # The real data in the database    # User_group: Refers to the UserGroup object. The class UserGroup object encapsulates (uid,catption,ctime,uptime)    print (row.user_group.uid)       # Gets the UID from the object, like    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 ()        # Second way: Via Foreign key field _id        user_group_id = 1    )

Reprint Source: http://blog.csdn.net/fgf00/article/details/53678205



Django Getting Started 4: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.