1、models.py
from django.db import models
# Create your models here.
class Student(models.Model):
s_name = models.CharField(max_length=16)
s_age = models.IntegerField(default=1)
2、python manage.py makemigrations
(venv) MacBookPro:HelloDjango zhangxm$ python manage.py makemigrations
Migrations for 'Two':
Two/migrations/0001_initial.py
- Create model Student
(venv) MacBookPro:HelloDjango zhangxm$
# Generated by Django 2.2.9 on 2020-01-22 02:28
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Student',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('s_name', models.CharField(max_length=16)),
('s_age', models.IntegerField(default=1)),
],
),
]
3、python manage.py migrate
(venv) MacBookPro:HelloDjango zhangxm$ python manage.py migrate
Operations to perform:
Apply all migrations: Two, admin, auth, contenttypes, sessions
Running migrations:
Applying Two.0001_initial... OK
(venv) MacBookPro:HelloDjango zhangxm$
4 DDL
-- auto-generated definition
create table Two_student
(
id integer not null
primary key
autoincrement,
s_name varchar(16) not null,
s_age integer not null
);
5、Django ORM CRUD
Two->>urls.py
from django.conf.urls import url
from Two import views
urlpatterns = [
url('^index/', views.index),
url('^addstudent/', views.addstudent),
url('^getstudents/', views.getstudents),
url('^updatestudent/', views.updatestudent),
url('^deletestudent/', views.deletestudent),
]
Two->>views.py
import random
from django.http import HttpResponse
from django.shortcuts import render
# Create your views here.
from Two.models import Student
def index(request):
return HttpResponse("Two index")
def addstudent(request):
student = Student()
student.s_name = "Jerry %d" % random.randrange(100)
student.save()
return HttpResponse("Add Success %s" % student.s_name)
def getstudents(request):
students = Student.objects.all()
for student in students:
print(student.s_name)
context = {
"hobby": "PlayGames",
"eat": "meat",
"students": students
}
#return HttpResponse("Students List")
return render(request, 'student_list.html', context=context)
def updatestudent(request):
student = Student.objects.get(pk=2)
student.s_name = 'Updated Name'
student.save()
return HttpResponse("Update Student Success")
def deletestudent(request):
student = Student.objects.get(pk=3)
student.delete()
return HttpResponse("Delete Student Success")
/->>templates->>student_list.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Student List</title>
</head>
<body>
this is student list page
{{ hobby }}
{#{{ students }}#}
<ul>
{% for student in students %}
<li>{{student.s_name }}</li>
{% endfor %}
</ul>
</body>
</html>