Django数据库操作增删改查和查询API

增删改查

Django中数据的增删改查操作如下:

我们以一个model:User为例,User有三个字段,一个是username、passwd、phonenumber

(1)增加一条记录

添加一个username、passwd、phonenumber字段值为s_username、s_passwd、s_phonenumber的记录


user=User()

user.username=s_username

user.passwd=s_passwd

user.phonenumber=s_phonenumber

user.save()

或

user=User(username=s_username,passwd=s_passwd,phonenumber=s_phonenumber)

user.save()

(2)删除记录

删除一条username为‘yy’的记录

User.objects.get(username='yy').delete()

删除一组记录,假设一个电话号码可以对应多个user,现在要删除电话号码为‘123456’的所有用户

User.objects.filter(phonenumber='123456').delete()

(3)修改记录

把username为‘dw’的记录的手机号修改为‘88888’

user=User.objects.get(username='dw')

user.phonenumber='88888'

user.save()

(4)查询记录

查询用username为‘dw’的记录

user=User.objects.get(username='dw')

用get查询出来的记录是一个User对象

查询phonenumber为‘88888’的所有用户

user=User.objects.filter(phonenumber='88888')

用filter查询的结果得到的是一个列表

批量操作参见 Django ORM 批量操作和外键查询

查询API

类型 | 描述

---|---
exact | 精确匹配: polls.get_object(id__exact=14).
iexact | 忽略大小写的精确匹配: polls.objects.filter(slug__iexact="foo") 匹配foo, FOO, fOo, 等.
contains| 大小写敏感的内容包含测试:
icontains|大小写不敏感的内容包含测试:
gt|大于: polls.objects.filter(id__gt=4).
gte|大于等于.
lt|小于.
lte |小于等于
ne| 不等于.
in| 位于给定列表中: polls.objects.filter(id__in=[1, 3, 4]) 返回一个 polls 列表(ID 值分别是 1或3或4).
startswith |大小写敏感的 starts-with: polls.objects.filter(question__startswith="Would"). (仅PostgreSQL 和MySQL支持. SQLite 的LIKE 语句不支持大小写敏感特性. 对Sqlite 来说,startswith 等于 istartswith)
endswith| 大小写敏感的 ends-with. (仅PostgreSQL 和 MySQL)
istartswith |大小写不敏感的 starts-with.
iendswith| 大小写不敏感的 ends-with.
range| 范围测试: polls.objects.filter(pub_date__range=(start_date, end_date)) 返回 pub_date 位于 start_date 和 end_date (包括)之间的所有民意测验
year| 对 date/datetime 字段, 进行精确的 年 匹配: polls.get_count(pub_date__year=2005).
month| 对 date/datetime 字段, 进行精确的 月 匹配:
day |对 date/datetime 字段, 进行精确的 日 匹配:
isnull| True/False; 做 IF NULL/IF NOT NULL 查询: polls.objects.filter(expire_date__isnull=True).

posted @ 2018-05-18 09:32  TasteL  阅读(303)  评论(0编辑  收藏  举报