创建模型类
class UserInfo(models.Model):
id = models.IntegerField()
username = models.CharField(max_length=32)
(注意在settings.py中注册新建的app)
然后执行迁移命令:
python manage.py makemigrations
python manage.py migrate
基本操作:
增加数据:
models.UserInfo.objects.create(username="root",password='123')
另一种创建数据方法:
obj = models.UserInfo(username='root1', password='123')
obj.save()
查询数据:
result = models.UserInfo.objects.all()
#这里返回的是一个QuerySet类型
for row in result:
print(row.id, row.username, row.password)
按条件查询:
result = models.UserInfo.objects.filter(username='root')
#这里返回的是一个QuerySet类型
for row in result:
print(row.id, row.username, row.password)
删除全部数据:
models.UserInfo.objects.all().delete()
按条件删除:
models.UserInfo.objects.filter(id=1).delete()
修改全部(更新):
models.UserInfo.objects.all().update(password=666)
更新部分:
models.UserInfo.objects.filter(username='root1').update(password=666)
参考自:https://blog.csdn.net/qq_41144008/article/details/78827272
models.UserInfo.object.filter(username = ' ',age = ' ') --> 等于 models.UserInfo.object.filter(age__gt = 2) --> 大于 models.UserInfo.object.filter(age__lt = 2) --> 小于 models.UserInfo.object.filter(age__gte = 2) -->大于等于 models.UserInfo.object.filter(age__lte =2) -->小于等于
moldes.UserInfo.object.filter().first() 获取一个对象