Definition and examples of Models basic fields in Django

jango Model field type and field parameters

The most important and only necessary thing in the model is the field definition of the database, the field is defined in the class attribute, and each field should be an instance of a Field class.

Common Field Types

DecimalField():小数必须给定2个参数max_digits(最大长度), decimal_places(保留小数位数)
AutoField():一个IntegerField,根据可用ID自动递增。如果没指定主键,就创建它自动设置为主键。
BooleanField:             布尔类型字段
CharField:                字符串类型字段
DateField:                日期字段
DateTimeField:            日期时间字段
EmailField:Email:        字段
FileField:                文件字段
FloatField:              (浮点数)小数字段
ImageField:               图片字段
IntegerField:             整数字段
IPAddressField:           IP字段
SmallIntegerField:        小整数字段
TextField:                文本字段
URLField:                 网址地址字段

Field parameter
ForeignKey.on_delete: When a ForeignKey deletes the referenced object, Django will emulate the behavior of the SQL constraint specified by the on_delete parameter.

CASCADE,           删除引用的对象时,也删除引用它的对象;
PROTECT,           通过抛出异常来禁止删除引用的对象;
OneToOneField(to, on_delete, parent_link = False):一对一
ForeignKey(to, on_delete):一对多
ManyToManyField(to):多对多
SET_NULL,           将引用设置为NULL,只有在null为True的情况下。
SET_DEFAULT,       设置默认值,ForeignKey必须设置默认值。
SET(...),           设置给定值。
DO_NOTHING,        不采取行动。如果数据库后端强制引用完整性,这将导致完整性错误,
除非手动向数据库字段添加
SQL on delete约束

Meta()

abstract          如果abstract=True,那么model为抽象基类;
app_label         在其他地方写了一个模型类,而这个模型类是属于myapp的,那么需要指定app_label='myapp'
db_table          用于指定自定义数据库表名的;
get_latest_by     由于Django的管理方法中有个lastest()方法,就是得到最近一行记录。如果你的数据模型中有 DateField 或 DateTimeField 类型的字段,你可以通过这个选项来指定lastest()是按照哪个字段进行选取的。
managed           由于Django会自动根据模型类生成映射的数据库表,如果你不希望Django这么做,可以把managed的值设置为False。
ordering          这个字段是告诉Django模型对象返回的记录结果集是按照哪个字段排序的。加负号为反序ordering = ['-create_time']
permissions       创建此对象时进入权限表的额外权限。 指定了一个附加权限: can_deliver_pizzas permissions = (("can_deliver_pizzas", "Can deliver pizzas"),)这是一个2-元素 tuple 的tuple或列表, 其中两2-元素 tuple 的格式为:(permission_code, human_readable_permission_name)。
unique_together   一起使用的字段名称集必须是唯一的,这是一个列表,这些列表在一起考虑时必须是唯一的  unique_together = [['driver', 'restaurant']]
verbose_name      给model类起一个更可读的名字:
verbose_name_plural   model的复数名称

QuerySet API methods

Field lookups: Field lookups are a way of specifying the contents of an SQL WHERE clause. They are specified as keyword arguments to the QuerySet method; the corresponding subset is found with the given constraints.

 普通查询
in:在给定的可迭代对象中
gt, gte, lt, lte:         大于,大于或等于,小于,小于或等于
range:                    给定对象范围内
isnull:                   是否为空
exact, iexact:            完全符合
contains, icontains:      包含匹配
startswith, istartswith:  开头
endswith, iendswith:      结尾
regex, iregex:            正则表达式
field 查询

聚合查询
Aggregate(*expressions, output_field = None, distinct = False, filter = None, ** extra)
聚合表达式是Func()表达式的一种特殊情况,查询需要一个聚合函数
Avg():返回给定表达式的平均值
Count():返回给定表达式的总计数
Max():返回给定表达式的最大值
Min():返回给定表达式的最小值
Sum():计算给定表达式的所有值的总和

Common query examples:

常用查询
School.objects.all()  #查询School表中所有数据
School.objects.get(school_name='北京大学')  #查询School表中学校名字为北京大学的数据
School.objects.filter(city='beijing')  #查询School表中city字段为beijing的数据
School.objects.exclude(city='beijing')  #查询city=beijing的数据
School.objects.filter(pk=1).values()  #查询pk=1的值
School.objects.values('city').distinct()  #去重
School.objects.order_by('pass_line')  # 排序,默认升序
School.objects.order_by('pass_line').reverse()#排序并使用reverse()进行翻转操作
School.objects.count()  #查询数据总数,默认id
School.objects.filter(city='beijing').first()  #查询city为beijing的第一个数据
School.objects.filter(city='beijing').last()  #查询city为beijing的最后一个数据
School.objects.filter(pass_line__gt=500).exists()  #查询是否存在pass_line高于500的数据,Ture
School.objects.filter(pass_line__gt=700).exists()  #查询是否存在pass_line高于700的数据 False

聚合查询
from django.db.models import Avg, Count, Max, Min, Sum

Student.objects.aggregate(Avg('score'))  #{'score__avg': 618.0}
Student.objects.aggregate(Count('score'))  #{'score__count': 3}
Student.objects.count()  #3
Student.objects.aggregate(Max('score'))  #{'score__max': 666}
Student.objects.aggregate(min_value=Min('score'))  #{'min_value': 560}
Student.objects.aggregate(sums=Sum('score'))  #{'sums': 1854}

Guess you like

Origin blog.csdn.net/qq_40267002/article/details/120569156