Python django-2

Source: Internet
Author: User

ORM Introduction
    • An important part of the MVC framework is the ORM, which implements the decoupling of the data model from the database, that is, the design of the data model does not need to rely on a specific database, simple configuration can easily change the database
    • ORM is the "object-relationship-mapping" abbreviation, the main tasks are:
      • Generate table structure based on the type of object
      • Convert an object, list operation, to an SQL statement
      • Convert the results of SQL queries to objects, lists
    • This greatly reduces the developer's workload and does not require the use of invalid labor due to database changes
    • The model in Django contains the fields and constraints that store the data, corresponding to the unique tables in the database

Using the MySQL Database
    • Installing the MySQL package in a virtual environment
pip install mysql-python
    • Create a database in MySQL
create databases test2 charset=utf8
    • Open the settings.py file, modify the databases entry
DATABASES = {    ‘default‘: {        ‘ENGINE‘: ‘django.db.backends.mysql‘,        ‘NAME‘: ‘test2‘,        ‘USER‘: ‘用户名‘,        ‘PASSWORD‘: ‘密码‘,        ‘HOST‘: ‘数据库服务器ip,本地可以使用localhost‘,        ‘PORT‘: ‘端口,默认为3306‘,    }}
Development process
    1. Defining model classes in models.py, requiring inheritance from Models.model
    2. Add an application to the Installed_app entry for the settings.py file
    3. Generate migration files
    4. To perform a migration build table
    5. Using model classes for CRUD operations
To generate a model class using a database
python manage.py inspectdb > booktest/models.py

 

Defining the Model
    • Defining a property in a model generates a field in a table
    • Django determines the following information based on the type of the property:
      • Types of supported fields for the currently selected database
      • Default HTML controls used when rendering management forms
      • Minimal validation at the administration site
    • Django adds auto-growing primary key columns to the table, each model can have only one primary key column, and if you use options to set a property as the primary key column, Django no longer generates the default primary key column
    • Attribute naming restrictions
      • cannot be a reserved keyword for python
      • Continuous underscores are not allowed due to Django query mode
Defining properties
    • The field type is required when defining attributes
    • The field type is defined in the Django.db.models.fields directory and is imported into the django.db.models for ease of use
    • How to use
      1. Import from django.db import models
      2. Through models. Field creates an object of the type of the fields, assigns a value to the property
    • For important data are tombstoned, do not do physical deletion, the implementation method is to define the Isdelete property, the type is Booleanfield, the default value is False
Field type
  • Autofield: A integerfield that grows automatically based on the actual ID, usually does not specify
    • If not specified, a primary key field is automatically added to the model
  • Booleanfield:true/false field, the default form control for this field is Checkboxinput
  • Nullbooleanfield: Supports NULL, TRUE, false three values
  • Charfield (max_length= character length): string, default form style is TextInput
  • TextField: Large text field, generally more than 4000 used, the default form control is textarea
  • Integerfield: Integer
  • Decimalfield (Max_digits=none, Decimal_places=none): decimal floating-point number represented using a Python decimal instance
    • Decimalfield.max_digits: Total number of digits
    • Decimalfield.decimal_places: Number of digits after the decimal point
  • Floatfield: Floating-point number represented by a Python instance of float
  • Datefield[auto_now=false, Auto_now_add=false]): Date represented using Python's datetime.date instance
    • Parameter datefield.auto_now: The field is automatically set to the current time each time the object is saved, the timestamp for "last modified", which always uses the current date and defaults to False
    • Parameter Datefield.auto_now_add: Automatically sets the current time when the object is created for the first time, the timestamp used to create it, always using the current date, and defaults to False
    • The default corresponding form control for this field is a textinput. Added a JavaScript-written calendar control at the admin site, and a "Today" shortcut button that contains an additional invalid_date error message key
    • Auto_now_add, Auto_now, and default these settings are mutually exclusive and any combination between them will result in incorrect results
  • Timefield: The time represented by the Datetime.time instance of Python, with the parameters Datefield
  • Datetimefield: The date and time represented by the Datetime.datetime instance of Python, with the parameters Datefield
  • Filefield: A field for uploading files
  • ImageField: Inherits all the properties and methods of Filefield, but verifies the uploaded object to ensure it is a valid image
Field options
    • Field options enable you to constrain a field
    • When a Field object is specified by the keyword argument
    • NULL: If the null value is stored as NULL in the database for True,django, the default value is False
    • Blank: If True, the field is allowed to be blank and the default value is False
    • Comparison: null is the concept of database category, blank is the category of form validation
    • Db_column: The name of the field, if not specified, the name of the property used
    • Db_index: If the value is True, an index is created in the table for this field
    • Default: Defaults
    • Primary_key: If true, the field becomes the primary key field of the model
    • Unique: If true, this field must have a unique value in the table
Relationship
    • The types of relationships include
      • ForeignKey: One-to-many, define fields on multiple sides
      • Manytomanyfield: Many-to-many, define fields in both ends
      • Onetoonefield: One-to-one, define fields on either end
    • You can maintain a recursive association relationship, using ' self ' as specified, see "autocorrelation"
    • With one access multi: object. Model class Lowercase _set
bookinfo.heroinfo_set
    • With one access one: object. Model Class Lowercase
heroinfo.bookinfo
    • Access ID: Object. Property _id
heroinfo.book_id
Meta options
    • Define the class meta in the model class to set meta information
    • Meta-Information db_table: Defining data table names, recommending lowercase letters, default names for data tables
<app_name>_<model_name>
    • Ordering: The default sort field of an object, gets the list of objects when used, receives the list of property components
class BookInfo(models.Model):    ...    class Meta():        ordering = [‘id‘]
    • String pre-plus-indicates reverse, no plus-indicates positive order
class BookInfo(models.Model):    ...    class Meta():        ordering = [‘-id‘]
    • Sorting increases the cost of the database
Sample Demo
    • Create a test2 project and create a booktest app that uses the MySQL database
    • Define a book Model
class BookInfo(models.Model):    btitle = models.CharField(max_length=20)    bpub_date = models.DateTimeField()    bread = models.IntegerField(default=0)    bcommet = models.IntegerField(default=0)    isDelete = models.BooleanField(default=False)
    • Hero model
class HeroInfo(models.Model):    hname = models.CharField(max_length=20)    hgender = models.BooleanField(default=True)    isDelete = models.BooleanField(default=False)    hcontent = models.CharField(max_length=100)    hbook = models.ForeignKey(‘BookInfo‘)
    • Define the index, detail view
    • index.html, detail.html templates
    • Configure URLs to complete the display of books and heroes
Test data
    • Test data for Model BookInfo
insert into booktest_bookinfo(btitle,bpub_date,bread,bcommet,isDelete) values(‘射雕英雄传‘,‘1980-5-1‘,12,34,0),(‘天龙八部‘,‘1986-7-24‘,36,40,0),(‘笑傲江湖‘,‘1995-12-24‘,20,80,0),(‘雪山飞狐‘,‘1987-11-11‘,58,24,0)
    • Test data for Model Heroinfo
insert into booktest_heroinfo(hname,hgender,hbook_id,hcontent,isDelete) values(‘郭靖‘,1,1,‘降龙十八掌‘,0),(‘黄蓉‘,0,1,‘打狗棍法‘,0),(‘黄药师‘,1,1,‘弹指神通‘,0),(‘欧阳锋‘,1,1,‘蛤蟆功‘,0),(‘梅超风‘,0,1,‘九阴白骨爪‘,0),(‘乔峰‘,1,2,‘降龙十八掌‘,0),(‘段誉‘,1,2,‘六脉神剑‘,0),(‘虚竹‘,1,2,‘天山六阳掌‘,0),(‘王语嫣‘,0,2,‘神仙姐姐‘,0),(‘令狐冲‘,1,3,‘独孤九剑‘,0),(‘任盈盈‘,0,3,‘弹琴‘,0),(‘岳不群‘,1,3,‘华山剑法‘,0),(‘东方不败‘,0,3,‘葵花宝典‘,0),(‘胡斐‘,1,4,‘胡家刀法‘,0),(‘苗若兰‘,0,4,‘黄衣‘,0),(‘程灵素‘,0,4,‘医术‘,0),(‘袁紫衣‘,0,4,‘六合拳‘,0)
Properties of the class
    • Objects: Is an object of type manager for interacting with the database
    • When you define a model class without specifying a manager, Django provides a manager named objects for the model class
    • Support for explicitly specifying the manager of the Model class
class BookInfo(models.Model):    ...    books = models.Manager()
    • When you specify a manager for a model class, Django no longer generates a default manager named objects for the model class
Manager Manager
    • The manager is the Django model interface for querying operations on the database, and each model of the Django application has at least one manager
    • The custom manager class is used primarily in two situations
    • Scenario One: Add an additional method to the manager class: See the "Create Object" form in the following two
    • Scenario Two: Modifying the original query set returned by the manager: overriding the Get_queryset () method
class BookInfoManager(models.Manager):    def get_queryset(self):        return super(BookInfoManager, self).get_queryset().filter(isDelete=False)class BookInfo(models.Model):    ...    books = BookInfoManager()
Creating objects
    • Django does not read and write to the database when the object is created
    • Call the Save () method to interact with the database and save the object to the database
    • Using keyword parameters to construct a model object is cumbersome, the following two types of recommendations are recommended
    • Description: The _init _ method has been models in the base class. Model for use in custom models,
    • Method One: Add a class method to the Model class
class BookInfo(models.Model):    ...    @classmethod    def create(cls, title, pub_date):        book = cls(btitle=title, bpub_date=pub_date)        book.bread=0        book.bcommet=0        book.isDelete = False        return book引入时间包:from datetime import *调用:book=BookInfo.create("hello",datetime(1980,10,11));保存:book.save()
    • Way two: Add a method to the custom manager
    • In the manager's method, you can get the model class that it belongs to by Self.model
class BookInfoManager(models.Manager):    def create_book(self, title, pub_date):        book = self.model()        book.btitle = title        book.bpub_date = pub_date        book.bread=0        book.bcommet=0        book.isDelete = False        return bookclass BookInfo(models.Model):    ...    books = BookInfoManager()调用:book=BookInfo.books.create_book("abc",datetime(1980,1,1))保存:book.save()
    • In mode two, you can call Self.create () to create and save the object without having to manually save ()
class BookInfoManager(models.Manager):    def create_book(self, title, pub_date):        book = self.create(btitle = title,bpub_date = pub_date,bread=0,bcommet=0,isDelete = False)        return bookclass BookInfo(models.Model):    ...    books = BookInfoManager()调用:book=Book.books.create_book("abc",datetime(1980,1,1))查看:book.pk
Properties of the instance
    • Doesnotexist: This exception is thrown when an object of the model does not exist when a single query is made, in conjunction with Try/except
Method of the instance
    • STR (self): Overrides the object method, which is called when the object is converted to a string
    • Save (): Saves the model object to the datasheet
    • Delete (): Removes the model object from the data table
Brief introduction
    • A query set represents a collection of objects obtained from a database
    • A query set can contain 0, one, or more filters
    • The filter restricts the results of the query based on the parameters given
    • From the SQL point of view, query sets and SELECT statements are equivalent, filters like where and limit clauses
    • Next, we discuss the following points of knowledge
      • Query set
      • Field query: comparison operator, F object, Q object
Query set
    • Calling the filter method on the manager returns the query set
    • The query set is filtered to return a new query set, so it can be written as a chain filter
    • Lazy execution: Creating a query set does not bring any database access until the data is called for access to the database
    • When to evaluate a query set: Iterate, serialize, and if
    • Method that returns a query set, called a filter
      • All ()
      • Filter ()
      • Exclude ()
      • Order_by ()
      • VALUES (): An object that forms a dictionary and then forms a list to return
    • Writing:
filter(键1=值1,键2=值2)等价于filter(键1=值1).filter(键2=值2)
    • Methods that return a single value
      • Get (): Returns an individual object that satisfies the condition
        • The model class is thrown if it is not found. Doesnotexist "exception
        • If multiple bars are returned, the model class is thrown. Multipleobjectsreturned "exception
      • COUNT (): Returns the total number of bars for the current query
      • First (): Returns the object
      • Last (): Returns the final object
      • Exists (): Determines whether there is data in the query set and returns True if any
Restricting query Sets
    • The query set returns a list that can be restricted by using subscripts, equivalent to the limit and offset clauses in SQL
    • Note: Negative indexes are not supported
    • Returns a new query set after using the subscript and does not execute the query immediately
    • If you get an object, use [0] directly, equivalent to [0:1].get (), but if there is no data, [0] throws a Indexerror exception, [0:1].get () throws a Doesnotexist exception
Caching of query sets
    • Each query set contains a cache to minimize access to the database
    • In a new query set, the cache is empty, the first time a query set is evaluated, a database query occurs, Django will query the results of the query set in the cache, and return the results of the request, and then evaluate the query set will reuse the cached results
    • Scenario One: This makes up two query sets, cannot reuse the cache, and each query will interact with the database once, increasing the load on the database
print([e.title for e in Entry.objects.all()])print([e.title for e in Entry.objects.all()])
    • Scenario two: Two cycles using the same query set, the second time using the data in the cache
querylist=Entry.objects.all()print([e.title for e in querylist])print([e.title for e in querylist])
    • When a query set is not cached: The cache is checked when only a portion of the query set is evaluated, but if this part is not in the cache, then the records returned by the query will not be cached, which means that using the index to limit the query set will not populate the cache, and if the data is already cached, use the data in the cache directly
Field Query
    • Implement the Where child name as a parameter to the method filter (), exclude (), get ()
    • Syntax: Property name __ comparison operator = value
    • Represents two underscores, the left side is the property name, and the right side is the comparison type
    • For foreign keys, use "Property name _id" to indicate the original value of the foreign key
    • Escape: The like statement is used in% with , matching the data in the% with , in the filter directly write, for example: Filter (title__contains= "%") =>where title as '%\%% ', indicating that the search header contains% of the
Comparison operators
    • Exact: Sentence, case sensitive, if not written " comparison operator", indicating the sentence
filter(isDelete=False)
    • Contains: Whether it is included, case sensitive
exclude(btitle__contains=‘传‘)
    • StartsWith, EndsWith: Case sensitive at the beginning or end of value
exclude(btitle__endswith=‘传‘)
    • IsNull, Isnotnull: Is null
filter(btitle__isnull=False)
    • Adding an I to the front means case insensitive, such as Iexact, Icontains, Istarswith, Iendswith
    • In: is included in the range
filter(pk__in=[1, 2, 3, 4, 5])
    • GT, GTE, LT, LTE: Greater than, greater than or equal, less than, less than or equal to
filter(id__gt=3)
    • Year, month, day, week_day, hour, minute, second: Operations on properties of a period type
filter(bpub_date__year=1980)filter(bpub_date__gt=date(1980, 12, 31))
    • Query across associative relationships: working with join queries
      • Syntax: Model class name < property name > < compare >
      • Note: There can be no __< compare > section, which means equals, result with inner join
      • Can be returned to use, that is, in the associated two models can be used
filter(heroinfo_ _hcontent_ _contains=‘八‘)
    • Shortcut to query: PK,PK represents primary key, the default primary key is ID
filter(pk__lt=6)
Aggregation functions
    • Use the aggregate () function to return the value of an aggregate function
    • Function: Avg,count,max,min,sum
from django.db.models import MaxmaxDate = list.aggregate(Max(‘bpub_date‘))
    • General usage of Count:
count = list.count()
F Object
    • You can use the model's field A to compare with field B, and if A is written to the left of the equals sign, B appears to the right of the equal sign and needs to be constructed by an F object
list.filter(bread__gte=F(‘bcommet‘))
    • Django supports using arithmetic operations on F () objects
list.filter(bread__gte=F(‘bcommet‘) * 2)
    • The F () object can also write "model class __ Column name" for the associated query
list.filter(isDelete=F(‘heroinfo__isDelete‘))
    • For date/time fields, you can perform operations with Timedelta ()
list.filter(bpub_date__lt=F(‘bpub_date‘) + timedelta(days=1))
Q Object
    • In the filter method, the keyword parameter query is merged into and
    • Requires an or query, using the Q () object
    • The Q object (DJANGO.DB.MODELS.Q) is used to encapsulate a set of keyword parameters that are the same as in the comparison operator
from django.db.models import Qlist.filter(Q(pk_ _lt=6))
    • The Q object can be combined using the & (and), | (or) operators.
    • When the operator is applied to a two Q object, a new Q object is generated
list.filter(pk_ _lt=6).filter(bcommet_ _gt=10)list.filter(Q(pk_ _lt=6) | Q(bcommet_ _gt=10))
    • Use the ~ (not) operator to indicate the inverse of the Q object before the
list.filter(~Q(pk__lt=6))
    • You can use &|~ to group together parentheses to construct complex Q objects for business
    • The filter function can pass one or more Q objects as positional parameters, and if there are multiple Q objects, the logic of these parameters is and
    • The filter function can mix the Q object with the keyword parameter, all parameters will be together, and the Q object must precede the keyword argument
Self-connect
    • For region information, a one-to-many relationship that uses a table to store all the information
    • Similar table structures are also used for categorical information, which allows for unlimited classification
    • Create a new model Areainfo, create a migration
class AreaInfo(models.Model):    atitle = models.CharField(max_length=20)    aParent = models.ForeignKey(‘self‘, null=True, blank=True)
    • Accessing associated objects
上级对象:area.aParent下级对象:area.areainfo_set.all()
    • Add test data (in Workbench, see "Provinces and Cities Mysql.txt")
    • Define the view area in booktest/views.py
from models import AreaInfodef area(request):    area = AreaInfo.objects.get(pk=130100)    return render(request, ‘booktest/area.html‘, {‘area‘: area})
    • Define Template area.html
<!DOCTYPE html>
    • Configure a new urlconf in the booktest/urls.py
urlpatterns = [    url(r‘^area/$‘, views.area, name=‘area‘)]


Python django-2

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.