django--orm--008

单表的增删改查

表结构

 代码表结构

class Account(models.Model):
    """账户表"""
    username = models.CharField(max_length=64,unique=True)
    password = models.CharField(max_length=255)
    email = models.EmailField(unique=True,null=True,blank=True)
    register_date = models.DateTimeField(auto_now_add=True)
    signature = models.CharField("签名",max_length=255,null=True,blank=True)

增加有2种方法

方法一:

a = Account(username="lisi11",password="123456",email="123456qwe@qq.com")
a.save()

方法二:

Account.objects.create(username="lisi111",password="123456",email="123456qwe1@qq.com")

实际编程,可以传个字典

Account.objects.create(**dic)

两种方法:

没有区别,随意使用哪种


更新有2种方法

方法一:单对单,效率更高

Account.objects.filter(username="li").update(email="test12345@126.com")

方法二:get只能取一条记录,是0或者多条都会报错

a = Account.objects.get(username="li")
a.email="test12345888@126.com"
a.save()

删除方法

Account.objects.filter(username='lisi111').delete()

查询

查询全部:

book_list=Account.objects.all()

查询切片

查询前几条:

book_list=Account.objects.all()[:3]

隔几个取:

book_list=Account.objects.all()[::2]

倒叙:

book_list=Account.objects.all()[::-1]

查询第一个:

book_list=Account.objects.first()

查询最后一个:

book_list=Account.objects.last()

已字典形式展示值:

book_list = Account.objects.filter(username='lisi').values("email")

print(book_list)

打印结果

<QuerySet [{'email': '123456@qq.com'}]>

book_list = Account.objects.filter(username='lisi').values("username","email")

print(book_list)“

打印结果

<QuerySet [{'username': 'lisi', 'email': '123456@qq.com'}]>

已元组形式展示值:

book_list = Account.objects.filter(username='lisi').values_list("username","email")

print(book_list)“

打印结果

<QuerySet [('lisi', '123456@qq.com')]

除了某字段全显示:

book_list = Account.objects.exclude(username='lisi').values("username","email")

统计数:

book_list = Account.objects.all().values("password").distinct().count()

模糊查询:

_gt大于等于

_lt小于等于

_contain 不区分小大写,包括,相当于like

_range 相当于between…………and…………

_in  在一个列表的范围

_startswith,_endswith  以什么开头,以什么结束

_istartswith,_iendswith 模糊以什么开头,以什么结束

上班求生存,下班求发展
原文地址:https://www.cnblogs.com/ljf520hj/p/11827897.html