07- achieve common queries and table relationships basics of Django framework

 

 

1. The common model field type https://docs.djangoproject.com/en/2.1/ref/models/fields/#field-types

2. The common parameters field of official documents: https://docs.djangoproject.com/en/2.1/ref/models/fields/#field-options

3. Common Queries to construct the QuerySet by the manager on the model class.

Manager on the model class is what? Model class .objects, <django.db.models.manager.Manager> Example

  • QuerySet represents a collection of objects in the database. Equivalent to the select statement. Inert, will not immediately operate the database, in the calculation, loop, slice, the index will execute select statement. Case:

    • first () Gets the first return of the object

    • last () Gets an object is returned last thought: collation? By default the primary key. By setting _meta

    • get (** kwargs) according to the given conditions, get an object if there are multiple objects that match an error message.

    • all () Gets all the records are returned queryset

    • filter (** kwargs) in accordance with the given conditions, obtaining a filtered queryset, and a plurality of connection conditions employed.

    • exclude (** kwargs) using a filter with a consistent approach, the role of think the contrary, it is excluded.

    • OR conditions used to connect multiple objects Q, django.db.models.Q example: Students.objects.filter (Q (age = 18 ) | Q (age = 19))

    • values (* fields) returns a queryset, returns a list of dictionaries instead of data objects. Examples: Students.objects.values ( 'name', ' age')

    • only (* fields) returns querySet, the object list, note must contain only the primary key field, more commonly used in the actual development process, the value of flexibility.

    • defer (* fields) specify the field you want to exclude. return a QuerySet, the opposite effect and only.

    • order_by (* fields) default given field are ordered according to the order before the field name with '-' represents the reverse order

    • Python slices and slice usage list similar support step, a negative index is not supported, when the amount of data as possible without steps, and slow. After the slicing, longer supported, additional filter conditions sorting, as it has been performed to return the list. Examples : Students.objects.all () [: 5: 2]

  • Common query filter, exclude, get,

  • Plus two underscores use, such as name__contains.

    • exact exact match

    • iexact case insensitive, query is LIKE

    • contains contains, query the BINARY is case sensitive.

    • icontains comprises not case-sensitive.

    • in parameter lists, tuples or query_set

    • range range

    • gt greater than

    • greater than or equal gte

    • lt is less than

    • less lte

    • startswith begins

    • istartswith start is not case sensitive

    • Endswith is ending

    • iendswith is not case-sensitive end

    • isnull True, False 对应 IS NULL, IS NOT NULL

  • Polymerization from django.db.models import Count, Avg, Max , Min, Sum by the aggregate method queryset Student.objects.aggregate (age_avg = Avg ( 'age ')) # calculate the average age, age_avg generate a key.

    • count

    • The average Avg

  • Packet, the polymerization binding Values, and annotate the polymerization process implemented with the query has several boys and girls have several

  • from django.db.model. import Count

  • Student.objects.values('sex').annotate(num=Count('sex'))

  • 4. The table of relations between

 

Common query method:

 

Common query:

 

Find the meaning of the object conditions are some of the parameters passed to the method above. The equivalent of the back of the SQL statement where clause conditions, the syntax for the field name __ rule (is not even attached to underscore oh)

Common field types are mapped:

 

Common field types:

  1. IntegerField: Integer mapped to a database of type int.

  2. CharField: character type, the type is mapped to a database varchar, the maximum length specified by max_length.

  3. TextField: text type, text type is mapped to the database.

  4. BooleanField: boolean, tinyint type is mapped to the database, when in use, passing True / False into it. If you want to be is empty, with NullBooleanField.

  5. DateField: date type, no time. Mapping to the database is date type,

    When in use, can be provided each time DateField.auto_now save the object, the field is automatically set to the current time. Automatically set the current time setting DateField.auto_now_add when the object is first created.

  6. DateTimeField: 日期时间类型。映射到数据库中的是datetime类型,

    在使用的时候,传递datetime.datetime()进去。

Field的常用参数:

primary_key: 指定是否为主键。

unique: 指定是否唯一。

null: 指定是否为空,默认为False。

blank: 等于True时form表单验证时可以为空,默认为False。

default: 设置默认值。

DateField.auto_now: 每次修改都会将当前时间更新进去,只有调用,QuerySet.update方法将不会调用。这个参数只是Date和DateTime以及TimModel.save()方法才会调用e类才有的。

DateField.auto_now_add: 第一次添加进去,都会将当前时间设置进去。以后修改,不会修改这个值

1.创建模型类

 

2.执行生成映射文件的命令后,查看数据表

 

3.插入数据.

 

4.查看插入的数据.

 

表关系的实现:

 

 

表关系的例子:

 

 

创建模型类:

 

外键和一对一关系的时候需要加on_delete选项,此参数为了避免两个表里的数据不一致问题,不然会报错!

一般使用CASCADE表示级联删除

 

查看数据库中创建的表:

写好模型类后,执行生成映射文件的命令.

 

执行完makemigrations和migrate的命令后,在数据库我们能看到5张表,其中多对多关系的ManyToManyField

方法自动生成了关系表.

Guess you like

Origin www.cnblogs.com/winfun/p/10966806.html