下面是步骤
- 先更新 urls.py 来添加新的url
from django.contrib import admin
from django.urls import path
from app01 import viewsurlpatterns = [path('demo/', views.demo),
]
- 在 models.py 里创建表
from django.db import models# Create your models here.
class UserInfo(models.Model):username = models.CharField(verbose_name="用户名", max_length=16)password = models.CharField(verbose_name="密码", max_length=64)age = models.IntegerField(verbose_name="年龄")class Role(models.Model):title = models.CharField(verbose_name="标题", max_length=16)
- 运行migration的命令创建第2步里的表
python manage.py makemigrationspython manage.py migrate
- 在 views.py 里创建一个函数
def demo(request):from app01 import models """#如果该app是在 apps 文件夹里,那么调用的时候得这么调用from apps.app01 import models"""# 1. 增加#models.Role.objects.create(title="管理员")#models.UserInfo.objects.create(username="root", password="123", age=18)models.UserInfo.objects.create(**{'username': 'dd','password': '434','age': 3})# 2. 删除#models.Role.objects.all().delete() # 删除该表的所有数据#models.Role.objects.filter(id=1).delete()#models.Role.objects.filter(id=1, title="管理员").delete()# 3. 修改#models.UserInfo.objects.all().update(age=93)#models.UserInfo.objects.filter(id=1).update(age=20, password='23') # 找到 id=1 的数据,将数据修改# 4. 查询# 返回的是 QuerySet 类型 = [obj, obj]v1 = models.UserInfo.objects.all() # 查询所有的数据for obj in v1:print(obj.id, obj.username, obj.password, obj.age)v2 = models.UserInfo.objects.filter(age = 20)for obj in v2:print(obj.id, obj.username, obj.password, obj.age)v3 = models.UserInfo.objects.filter(id=3).first()if v3:print(v3.id, v3.username, v3.password, v3.age)return HttpResponse("测试")
- 可以通过查看 sqlite 的表看结果
如果在 views.py 文件里,出现类似下面这种错误
RuntimeError: Model class assetManagement.models.Admin doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.
就代表在 views.py 文件里对应的函数没有 return
# 在 views.py 文件里from apps.assetManagement import models# Create your views here.
def example(request):models.Admin.objects.create(username="root", password="123")models.Admin.objects.create(username="root1", password="234")return HttpResponse("测试成功!") # 添加这一行,就可解决问题
点个赞呗~