1.将应用(如learn)添加到安装应用配置中
将我们新建的应用(learn)添加到 settings.py 中的 INSTALLED_APPS中,告诉Django有这么一个应用。
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'learn',]
2. 在应用下的model添加表learn/model.py:
from django.db import models# Create your models here.class People(models.Model): name = models.CharField(max_length=30) age = models.IntegerField()
3.生成表:
python manage.py migrate
4. 在learn/view.py中添加操作:
from django.shortcuts import render# Create your views here.from django.http import HttpResponsefrom django.http import HttpResponseRedirectfrom django.urls import reversefrom learn.models import Peopledef index(request): # People.objects.create(name='michaelshu', age=12) # People.objects.get_or_create(name="WZT", age=23) p = People(name='WZ', age=23) p.save() #p = People.objects.all() #return HttpResponse(p[0].age) # 方法 3 #p1 = People() #p1.name = "WeizhongTu1" #p1.age = 23 #p1.save() #return HttpResponse(p1.id) # get operation # p = People.objects.get(name='WT') # return HttpResponse(p.age)
5. 查看数据库表是否添加成功: