1. 增
class Role(models.Model):
title = models.CharField(verbose_name="角色", max_length=32)
od = models.IntegerField(verbose_name="排序", default=0)
def str(self):
return "{}-{}-{}".format(self.id, self.title, self.od)
方法一:
obj1 = models.Role.objects.create(title="管理员", od=1)
obj1 = models.Role.objects.create(**{"title":"管理员", "od":1}) # 字典传值
方法二:
obj = models.Role(title="管理员", od=1) # 此时数据只在内存中
obj.od = 2 # 还可以修改
obj.save() # 写入到数据库
2. 删除
models.Role.objects.filter(id=1).delete()
models.Role.objects.filter(title="管理员").delete()
3. 修改
models.Role.objects.all().update(od=99)
models.Role.objects.filter(id=1).update(od=99, title="管理员")
models.Role.objects.filter(id=1).update(**{"title":"管理员", "od":1}) # 字典传值
4. 查询
v1 = models.Role.objects.all()
for obj in v1:
print(obj.id, )
v2 = models.Role.objects.filter(od=99, id=7) # where id=7
for obj in v2:
print(obj.id, )
v3 = models.Role.objects.filter(od__gt=2) # where od>2
print(v3.query) # 查看sql语句
v4 = models.Role.objects.filter(od__gte=2) # where od>=2
v3 = models.Role.objects.filter(od__lt=2) # where od<2
v4 = models.Role.objects.filter(od__lte=2) # where od<=2
v3 = models.Role.objects.filter(id__in=[2,4,6]) # where id=2 and id=4 and id=6
v3 = models.Role.objects.filter(title__contains="管")
v3 = models.Role.objects.filter(title__startswith="管")
v3 = models.Role.objects.filter(title__isnull=True)
v3 = models.Role.objects.exclude(id=99) # id不等于99
标签:title,models,od,改查,django,objects,Role,增删,id
From: https://www.cnblogs.com/jackchen28/p/18341637