Python Learning Path Web Framework continued

Source: Internet
Author: User

Model

So far, when our program involves database-related operations, we usually do this:

    • Create databases, Design table structures and fields
    • Use MYSQLDB to connect to a database and write data access layer code
    • The business logic layer to invoke the data access layer to perform database operations

Django uses a new approach, namely: Relational object Mapping (object relational Mapping, or ORM).

Php:activerecord

Java:hibernate

C#:entity Framework

Django follows the code Frist principle of automatically generating database tables based on classes defined in your code.

First, create a table

1. Basic structure

From django.db import Models   class UserInfo (models. Model):    name = models. Charfield (max_length=30)    email = models. Emailfield ()    memo = models. TextField ()

2. More fields

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) 13, models.  GenericipaddressfieldString types (IP4 and IP6 are optional) parameters protocol can be: both, IPv4, IPv6 validation, according to 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

3. More parameters

1, whether the field in the Null=true database can be empty 2, Blank=true Django Admin to add data when you can allow null value 3, Primary_key = False primary key, after the Autofield set the primary key, will replace the original self-increment ID column 4, Auto_now and Auto_now_add auto_now   automatically created---whether added or modified, is the time of the current operation Auto_now_add  automatically created---is always created at the time of 5, Choicesgender_ CHOICE = (U '        M ', U ' Male '),        (U ' F ', U ' Female '),    gender = models. Charfield (max_length=2,choices = gender_choice) 6, Max_length7, default value 8, verbose_name admin field display name 9, name|db_ Field name in column database 10, unique=true not allowed to repeat 11, Db_index = True Database index 12, editable=true in admin can edit 13, error_messages=none error prompt 1 4, Auto_created=false automatically create 15, Help_text in admin tips help information 16, validators=[]17, upload-to

2. Even table structure

    • One-to-many: models. ForeignKey (Other tables)
    • Many-to-many: models. Manytomanyfield (Other tables)
    • One to one: models. Onetoonefield (Other tables)

Application Scenarios:

One-to-many: when a row of data is created in a table, there is a single selection of drop-down boxes (which can be repeatedly selected) For example: When creating user information, you need to select a user type of "normal user" "Gold user" "Platinum User" and so on. Many-to-many: creating a row of data in a table is a drop-down box with multiple choices for example: Create user information and need to specify multiple hobbies for users one-to-one: when you create a row of data in a table, There is a single-selection drop-down box (the contents of the drop-down box are used once to disappear. For example: A table with 10 columns of data saves relevant information, after a period of time, 10 columns do not meet the requirements, you need to add 5 columns of data to the original table

Second, the Operation table

1. Basic operation

# #    #    # # # # models. Tb1.objects.create (c1= ' xx ', c2= ' oo ')  adds a piece of data that can accept the dictionary type data **kwargs    # obj = models. TB1 (c1= ' xx ', c2= ' oo ')    # Obj.save () #    Check    #    # models. Tb1.objects.get (id=123)         # Get a single data, no error (not recommended)    # models. Tb1.objects.all ()               # gets all    # models. Tb1.objects.filter (Name= ' seven ') # gets the data for the specified condition    # delete    #    # models. Tb1.objects.filter (Name= ' seven '). Delete () # Deletes the data for the specified condition    # change    # models. Tb1.objects.filter (Name= ' seven '). Update (gender= ' 0 ')  # Updates the data for the specified condition and supports **kwargs    # obj = models. Tb1.objects.get (id=1)    # obj.c1 = ' 111 '    # Obj.save ()                                                 # Modify Single data

2. Advanced operation (great double underline)

Connect fields to corresponding operations with double underlines

# Get number # # # models. Tb1.objects.filter (Name= ' seven '). Count () # is greater than, less than # # models. Tb1.objects.filter (id__gt=1) # Gets the value of ID greater than 1 # models. Tb1.objects.filter (id__lt=10) # Gets the value of the ID less than 10 # models. Tb1.objects.filter (id__lt=10, id__gt=1) # Gets the value of ID greater than 1 and less than 10 # in # # models. Tb1.objects.filter (Id__in=[11, 22, 33]) # Gets the data # models with the ID equal to 11, 22, 33. Tb1.objects.exclude (id__in=[11, [+]) # # Not in # contains # # models. Tb1.objects.filter (name__contains= "Ven") # models. Tb1.objects.filter (name__icontains= "Ven") # Icontains case insensitive # models. Tb1.objects.exclude (name__icontains= "Ven") # range # # models.    Tb1.objects.filter (Id__range=[1, 2]) # range Bettwen and # other similar # # Startswith,istartswith, EndsWith, Iendswith, # ORDER BY # # models. Tb1.objects.filter (Name= ' seven '). order_by (' ID ') # ASC # models. Tb1.objects.filter (Name= ' seven '). Order_by ('-id ') # desc # limit, offset # # models. Tb1.objects.all () [10:20] # GROUP by from Django.db.models import Count, Min, Max, Sum # models. Tb1.objects.filter (c1=1). VALUES (' ID '). Annotate (C=count (' num ')) # select "App01_tb1". " ID ", COUNT (" App01_tb1 "." Num ") as" C "from" App01_tb1 "WHERE" app01_tb1 "." C1 "= 1 GROUP by" app01_tb1 "." Id

3, even table operation (great double underline)

Use double underscores and _set to connect the operations between tables

Class UserProfile (models. Model): User_info = models. Onetoonefield (' UserInfo ') Username = models. Charfield (max_length=64) password = models. Charfield (max_length=64) def __unicode__ (self): return Self.usernameclass UserInfo (models. Model): User_type_choice = ((0, U ' normal user '), (1, u ' Admin user '),) User_type = models. Integerfield (choices=user_type_choice) name = models. Charfield (max_length=32) email = models. Charfield (max_length=32) address = models. Charfield (max_length=128) def __unicode__ (self): return Self.nameclass UserGroup (models. Model): Caption = models. Charfield (max_length=64) User_info = models. Manytomanyfield (' UserInfo ') def __unicode__ (self): return Self.captionclass Host (models. Model): hostname = models. Charfield (max_length=64) IP = models. Genericipaddressfield () User_group = models. ForeignKey (' UserGroup ') def __unicode__ (self): return self.hostname

One-to-one operation

User_info_obj = models. UserInfo.objects.filter (id=1). First () Print User_info_obj.user_typeprint user_info_obj.get_user_type_display () Print User_info_obj.userprofile.password User_info_obj = models. UserInfo.objects.filter (id=1). VALUES (' email ', ' userprofile__username '). First () print User_info_obj.keys () print User_info_obj.values ()

One-to-many

Similar to one-to-one 1, the search condition uses __ Connection 2, gets the value to use.    Connection

Many-to-many operations

Similar to one-to-one 1, the search condition uses __ Connection 2, gets the value to use.    Connection

Other operations

# f Use the value of the query condition    #    # from Django.db.models import F    # models. Tb1.objects.update (num=f (' num ') +1)    # Q Build search condition from    django.db.models import Q    # con = q ()    #    # q1 = q ()    # q1.connector = ' OR '    # q1.children.append ((' id ', 1))    # q1.children.append (' id ', ') #    Q1.children.append (' id ', 9) # #    q2 = Q ()    # q2.connector = ' OR '    # q2.children.append ((' C1 ', 1)) c16/># Q2.children.append ((' C1 ', Ten)) #    Q2.children.append ((' C1 ', 9)) # #    con.add (Q1, ' and ')    # Con.add (Q2, ' and ')    #    # models. Tb1.objects.filter (Con)    #    # from django.db import Connection    # cursor = Connection.cursor ()    # Cursor.execute ("" "SELECT * from TB WHERE name =%s" "", [' Lennon '])    # row = Cursor.fetchone ()

Note: the "_set" in Xx_set is a fixed collocation of many-to-many

Form

The form in Django typically has two functions:

    • Enter HTML
    • Validating user input
#!/usr/bin/env python#-*-coding:utf-8-*-import refrom Django import formsfrom django.core.exceptions import Validation Errordef mobile_validate (value): Mobile_re = Re.compile (R ' ^ (13[0-9]|15[012356789]|17[678]|18[0-9]|14[57]) [0-9]{8}$ ' If not Mobile_re.match (value): Raise ValidationError (' Phone number format error ') Class PublishForm (forms. Form): User_type_choice = ((0, U ' normal user '), (1, u ' Admin user user '), User_type = forms.                                                                  Integerfield (Widget=forms.widgets.select (Choices=user_type_choice, Attrs={' class ': "Form-control"})) title = forms. Charfield (max_length=20, min_length=5, error_messages={' Required ': U                                            ' Title cannot be empty ', ' min_length ': U ' title is at least 5 characters ', ' Max_length ': U ' title up to 20 characters '}, widget=forms.                   TextInput (attrs={' class ': "Form-control",                                       ' Placeholder ': U ' title 5-20 characters '}) Memo = forms. Charfield (Required=false, max_length=256, Widget=forms.widgets.textare A (attrs={' class ': "Form-control no-radius", ' placeholder ': U ' detailed description ', ' Rows ': 3})) phone = forms.                            Charfield (Validators=[mobile_validate,], error_messages={' Required ': U ' phone cannot be empty '}, Widget=forms. TextInput (attrs={' class ': "Form-control", ' placeholder ': U ' mobile number '} ) Email = forms.                            Emailfield (Required=false, error_messages={' Required ': U ' mailbox cannot be empty ', ' invalid ': U ' mailbox format error '}, Widget=forms. TextInput (attrs={' class ': "Form-control", ' placeholder ': U ' mailbox '}))

The contents of the view are as follows:

def publish (Request):    ret = {' status ': False, ' data ': ', ' Error ': ', ' Summary ': '}    if Request.method = = ' POST ':        request_form = publishform (Request. POST)        if Request_form.is_valid ():            request_dict = Request_form.clean ()            print request_dict            ret[' Status '] = True        else:            error_msg = Request_form.errors.as_json ()            ret[' error '] = json.loads (error_msg)    return HttpResponse (Json.dumps (ret))

Extension: Modelform

When you use the model and form, you need to define the field and specify the type, and you can omit the definition of the From field by Modelform

Class Adminmodelform (forms. Modelform):          class Meta:        model = models. Admin        #fields = ' __all__ ' fields        = (' username ', ' email ')                  widgets = {            ' email ': forms. Passwordinput (attrs={' class ': "Alex"}),        }

 

 

Python Learning Path Web Framework continued

Related Article

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.