——————- Use the MySql database ——————-


1. Download the mysql-Python package


pip install mysql-python

2. Create a database in mysql


create databases test2 charset=utf8

3. Modify setting.py


1, the ‘ENGINE’ : ‘the django. Db. Backends. Mysql,


2, ‘NAME’ : ‘test2’,


3, the ‘HOST’ : ‘localhost’


4, ‘POST’ : ‘3306’


5, ‘USER’:’ USER name ‘


6. ‘PASSWORD’:’ PASSWORD’

4. Generate migration files


python manage.py makemigrations

5. Migrate files


python manage.py migrate

6. Curd operations using model classes


——————- Define the model


Every application has a model.py file that references from Django. db import models. Create an object of Field type with models.Field and assign the value to the property

2, define the corresponding Model class inheritance (models.model)



——————- Defines the attribute ——————-


1. Field type


1. AutoField: An IntegerField that grows automatically based on the actual ID. If not specified, a primary key field is automatically added to the model.


BooleanField: true/false field, for which the default form control is CheckboxInput.


3. NullBooleanField: Supports null, true, and false values.


CharField(max_length= character length) : string. The default form style is TextInput.


5. TextFiled: Large text field, generally used over 4000, the default form control is Textarea.


6. IntegerField: an integer.


DecimalField(max_digits=None,decimal_places=None) : Decimal floating point number represented by python’s Decimal instance.


Max_digits: total number of digits


2. Decimal_places: The number of digits after the decimal point


8. FloadField: a floating point number represented by a Float instance of Python.


DateField[auto_now=False,auto_now_add=False] : specifies the date represented by the Python datetime.date instance.


Auto_now: This field is automatically set to the current time each time an object is saved. It is used for the “last modified” timestamp, which always uses the current date and defaults to false


Datefield. auto_now_add: The timestamp used for creation, which is automatically set to the current time when the object is first created, always uses the current date and defaults to false


3. The default form control for this field is a TextInput. Added a JavaScript written calendar control to the admin site and a “Today” shortcut button that includes an additional Invalid_date error message key


4. The auto_now_add, auto_NOW, and default Settings are mutually exclusive, and any combination of them will produce incorrect results


TimeField: The time represented by the Python datetime.time instance, with the same argument as DateField


DateTimeField: The date and time represented by Python’s datetime.datetime instance, with the same parameters as DateField


FileField: a field used to upload files


ImageField: Inherits all FileField attributes and methods, but verifies the uploaded object to make sure it is a valid image

2. Field options


Null: If True, Django stores null values into the database. The default value is False


Blank: If True, this field is allowed to be blank. The default value is False


3. Contrast: NULL is a database category, blank is a form validation category


Db_column: specifies the name of the column. If not specified, use the name of the property


Db_index: If True, create an index for this field in the table


6. Default: indicates the default value


7. Primary_key: If True, this field becomes the primary key field of the model


8, unique: If True, this field must have a unique value in the table

3, relationship,


1. Relationship types


ForeignKey: Many-to-one


ManyToManyField: Many-to-many


OneToOneField: One on one


2, can maintain recursive relationship, using ‘self’ specified

4. Meta-options


1. Define class Meta in the model class to set the Meta information

class BookInfo(models.Model):


.


class Meta():


Db_tables: define data table names,


ordering = [‘id’]

2, db_tables: define table name: default

3. Ordering = [‘id’] : this is the default ordering field of an object. If a string is preceded by a ‘-‘, it is in reverse order; if not, it is in positive order. Note sorting will add some overhead to the database



——————- Define manager


1. When you define a model class without specifying a manager, Django provides a manager named Objects for the model class


class BookInfo(models.Model):


.


books = models.Manager()

2. Manager


The manager is the interface through which Django models perform database queries. Every Django application has at least one manager

2. Custom manager classes are used in two main cases


Add additional methods to the manager class.


For example, create a method to add data quickly.


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 book

class BookInfo(models.Model):


.


books = BookInfoManager()

Object when called:


Call: book = book. Books. Create_book (” ABC “, a datetime,1,1 (1980))


Save: book. The save ()

2. Modify the original queryset returned by the manager by 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()





3. Object creation


First, When creating objects, Django doesn’t read or write to the database. Only the save() method is called to interact with the database to save the object to the database

2, try not to rewrite __init__ method, can create a class method or custom management class to create the corresponding object:


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


Import time package: from datetime import *


Call: book = BookInfo. Create (” hello “, a datetime (1980, 11));


Save: book. The save ()

Add a method to the custom manager


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 book

class BookInfo(models.Model):


.


books = BookInfoManager()


Call: book = book. Books. Create_book (” ABC “, a datetime,1,1 (1980))


Save: book. The save ()

4. Instance attributes:


DoesNotExist: when a single query is made, the object of the model DoesNotExist, this exception will be raised, combined with try/except.

5. Method of instance


STR (self) : Overrides the object method, which is called when an object is converted to a string


Save () : Saves the model object to the data table


Delete () : Deletes the model object from the table



——————- Model query ——————-


1. Query set


A query set represents a collection of objects retrieved from a database, which may contain zero, one, or more filters.

2. Features:


1. The manager obtains the corresponding query set from the database after calling the filtering method. The query set can call the filtering method many times to form chain filtering.

Lazy execution: Creating a query set does not bring any access to the database until the data is called.

3. Filter:


1. All () : returns all data;





2. Filter () : filter the query set according to the conditions;


Filter (key 1= value 1, key 2= value 2) is equivalent to filter(key 1= value 1).filter(key 2= value 2)





3, exclude() : conditional query





4, order_by() : specify attributes to sort;





Values () : an object forms a dictionary and is returned as a list;

6. Limit and offset in database


Returns a new query set after using the subscript. The query is not executed immediately.

2. The query set returns a list, which can be obtained by subscript, equivalent to limit and offset in the database.

3, If you get an object, use [0] directly, equivalent to [0:1].get(), but if there is no data, [0] raises IndexError, [0:1].get() raises DoesNotExist exception.

4. Note: Negative indexes are not supported.

4, return a single value method:


1. Get () : returns a single object that meets the condition


Raises the “model class” if not found. Abnormal DoesNotExist”

If more than one is returned, the “model class” is raised. Abnormal MultipleObjectsReturned”





2. Count () : Returns the total number of queries





3. First () : Returns the first object





4. Last () : Returns the last object





5. Exists () : checks whether there is data in the query set. If there is data in the query set, returns True

5. Cache of query set:


1. Each query set contains a cache to minimize database access

In a new query set, the cache is empty. The first time a query set is evaluated, a database query takes place. Django stores the query result in the query set cache and returns the requested result

3, this constitutes two query sets, can not reuse the cache, each query will be an interaction with the database, increasing the database load


print([e.title for e in Entry.objects.all()])


print([e.title for e in Entry.objects.all()])

4. Loop through the same query set twice, using cached data the second time


querylist=Entry.objects.all()


print([e.title for e in querylist])


print([e.title for e in querylist])

5. The cache is checked when only part of the query set is evaluated, but if that part is not in the cache, the records returned by subsequent queries will not be cached. This means that using indexes to limit the query set will not populate the cache, and if that part of the data is already cached, the data in the cache will be used

6, field query:


Implement the where subname as an argument to filter(), exclude(), and get()

2, syntax: attribute name __ comparison operator = value

3. Two underscores, attribute name on the left and comparison type on the right

4. For a foreign key, use attribute _id to indicate the original value of the foreign key

Filter (title__contains=”%”)=>where title like ‘%\%%’, where title like ‘%\%%’

6, comparison operator:


1. Exact: represents judgment and is case-sensitive. If the comparison operator is not written, it is judged and so on


filter(isDelete=False)


filter(name__exact=’w’)

2, contains: whether contains, case sensitive


Exclude (btitle__contains = ‘pass’)

3. Startswith and endswith: Start or end with value and are case-sensitive


Exclude (btitle__startswith = ‘pass’)


Exclude (btitle__endswith = ‘pass’)

4. Isnull, isnotnull: indicates whether the value isnull


filter(btitle__isnull=False)

5. Use “I” to indicate case insensitive, such as iexact, icontains, istarswith, iendswith

6. In: Whether it is included in the scope


filter(pk__in=[1, 2, 3, 4, 5])

7, GT, GTE, LT, LTE: greater than, greater than or equal to, less than or equal to


filter(id__gt=3)

8. Year, month, day, week_day, hour, minute, second: computes attributes of day types


filter(bpub_date__year=1980)


filter(bpub_date__gt=date(1980, 12, 31))

9, query shortcut: pk, pk indicates primary key, default primary key is id


filter(pk__lt=6)

7. Cross-association query: handle join query


1. Syntax: model class name < attribute name > < comparison >

Inner join = inner join = inner join

3. Reversible use, that is, it can be used in both associated models

4. Examples:


Filter (heroinfo__hcontent__contains = ‘8’)

2. Aggregate function


1. Use aggregate() to return the value of the aggregate function

2. Functions: Avg, Count, Max, Min, Sum

3. Examples:


from django.db.models import Max


maxDate = list.aggregate(Max(‘bpub_date’))

count = list.count()

3. F object


1. Field A of the model can be compared with field B. If A is written on the left side of the equal sign, B appears on the right side of the equal sign, which needs to be constructed by F object


list.filter(bread__gte=F(‘bcommet’))

Django supports arithmetic operations on F() objects


list.filter(bread__gte=F(‘bcommet’) * 2)

3, F() object can also be written as “model class __ column name” for associated query


list.filter(isDelete=F(‘heroinfo__isDelete’))

4. For date/time fields, timedelta() can be used


list.filter(bpub_date__lt=F(‘bpub_date’) + timedelta(days=1))

4. Q object


1. In the filter method, the keyword parameter query will be combined with And

2, need to perform or query, use Q() object

3. The Q object (django.db.models.q) encapsulates a set of keyword arguments that are the same as those in the comparison operator


from django.db.models import Q


list.filter(Q(pk_ _lt=6))

4, Q object can use & (and), | (or) operator

5. When the operator is applied to two Q objects, 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))

6. Use the ~ (not) operator to indicate the negation before the Q object


list.filter(~Q(pk__lt=6))

7, you can use & | ~ combined with parentheses to group, complex structure business Q object

8. Filter functions can pass one or more Q objects as positional arguments. If there are more than one Q object, the logic of these arguments is and

Filter functions can use a mixture of Q objects and keyword arguments. All arguments will be and together. Q objects must precede keyword arguments



——————- Automatic connection ——————-


1. Application scenarios


1. For the locale information, belong to one-to-many relationship, use a table, store all information

2. A similar table structure is also applied to classification information, which can achieve infinite classification

2. Foreign key definitions


class AreaInfo(models.Model):


atitle = models.CharField(max_length=20)


aParent = models.ForeignKey(‘self’, null=True, blank=True)

3. Access associated objects


1. Superior object: area.aparent


Area.areainfo_set.all ()

4, the instance,


from models import AreaInfo


def area(request):


area = AreaInfo.objects.get(pk=130100)


return render(request, ‘booktest/area.html’, {‘area’: area})

Data in the template page


{%for a in area.areainfo_set.all%}


<li>{{a.atitle}}</li>


{%endfor%}

For more free technical information: annalin1203