1、model关系
①ForeignKey,多对1
ForeignKey(to=关联model,to_field=“关联键”,on_delete=“级联删除选项”)
models.ForeignKey(to=User,to_field="id",on_delete=models.CASCADE)
②OneToOneFiled,1对1
OneToOneField(to=关联model,to_field="关联键",on_delete="级联删除选项")
③ManyToManyField,多对多
ManyToManyField(to=关联model)
2、模型API-单实例
- 类名.objects.get(filed=val,field1=val1)
- 等同于增加where,多个查询条件逗号分隔,逻辑运算为and
- 查询不到或多条记录抛出异常
3 、模型api-queryset
-
列表显示全部记录 r = Topic.objects.all()
-
打印输出查询语句,适用于QuerySet
print(r.query) -
倒序列表(model中必须定义排序规则)
Topic.objects.revers() -
自定义排序
Topic.objects.order_by(“user”,"-id") -
投影操作-设置显示字段列表
#返回字典
Topic.objects.values(“title”,“content”)
#返回元祖
Topic.objects.values_list(“title”,“content”) -
去重操作
Topic.objects.distinct()
Topic.objects.values(“title”).distinct() -
切片操作,索引不支持负数,