创建模型
from django.db import models
# Create your models here.
class Grade(models.Model):
g_name = models.CharField(max_length=32)
class Student(models.Model):
s_name = models.CharField(max_length=16)
s_grade = models.ForeignKey(Grade,on_delete=models.CASCADE)
class Person(models.Model):
p_name = models.CharField(max_length=16,unique=True)
p_age = models.IntegerField(default=18,db_column='age')
#False代表是男
p_sex = models.BooleanField(default=False,db_column='sex')
class Meta:
db_table = 'People'
这里做了一些限制,并且将数据库表的名字改为People
设置总路由和分路由
总路由
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path('app/', include('app.urls')),
]
分路由
from django.contrib import admin
from django.urls import path,include
from app import views
urlpatterns = [
path('getgrade/', views.get_grade),
path('addperson', views.add_person),
path('getperson', views.get_person)
]
设置好views.py
from django.shortcuts import render
from app.models import Student,Person
from django.http import HttpResponse
import random
# Create your views here.
def get_grade(request):
student = Student.objects.get(id=2)
grade = student.s_grade
return HttpResponse(grade.g_name)
def add_person(request):
for i in range(15):
person = Person()
flag = random.randrange(100)
person.p_name = "zhangsan%d" %flag
person.p_age = flag
person.p_sex = flag % 2
person.save()
return HttpResponse("批量添加成功")
def get_person(request):
person = Person.objects.filter(p_age__gt=18)
context = {
"person":person
}
return render(request, 'person_list.html', context=context)
在根目录下设置好模板文件夹templates,注意settings.py的设置
模板文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
{% for i in person %}
{{i.p_age}}
{% endfor %}
</body>
</html>
settings.py的设置
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR), 'templates'],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]