Django入门学习——创建模型类

tep1:创建Django项目:

django-admin startproject test1

注:在有权限的目录下创建

step2:打开PyCharm配置虚拟环境:

File——Project:projects2——Project interpreter——2.7.6 virtualenv at ~/.virtualenvs/h4——OK/Apply

step3:创建应用:

python manage.py startapp booktest

step4:在booktest目录下的models.py文件中创建模型类

 
  1. from django.db import models

  2.  
  3. class BookInfo(models.Model):

  4. btitle = models.CharField(max_length=10)

  5. bpub_date = models.DateTimeField()

  6. def __str__(self):

  7. return self.btitle.encode('utf-8')

  8. class HeroInfo(models.Model):

  9. hname = models.CharField(max_length=10)

  10. hgender = models.BooleanField()

  11. hcontent = models.CharField(max_length=1000)

  12. hbook = models.ForeignKey(BookInfo)

  13. def __str__(self):

  14. return self.hname.encode('utf-8')

step5:把应用注册到项目中,/test1/test1/settings.py

 
  1. # Application definition

  2.  
  3. INSTALLED_APPS = (

  4. 'django.contrib.admin',

  5. 'django.contrib.auth',

  6. 'django.contrib.contenttypes',

  7. 'django.contrib.sessions',

  8. 'django.contrib.messages',

  9. 'django.contrib.staticfiles',

  10. 'booktest',

  11. )

step5:生成迁移文件:

python manage.py makemigrations

step5:迁移:

python manage.py migrate

step6:开启shell

python manage.py shell

step7:添加、查询、删除图书信息:

 
  1. from booktest.models import BookInfo,HeroInfo

  2. from django.utils import timezone

  3. from datetime import *

 
  1. #添加图书信息

  2. b = BookInfo()

  3. b.btitle = 'Gone with the Wind'

  4. b.bpub_date = datetime(year=1936,month=1,day=1)

  5. b.save()

 
  1. #查询所有图书信息

  2. BookInfo.objects.all()

 
  1. #查找图书信息

  2. b = BookInfo.objects.get(pk=1)

 
  1. #删除图书信息

  2. b.delete()

step8:开启服务:

python manage.py runserver 8080

注:可以加端口8080,也可以不加

猜你喜欢

转载自blog.csdn.net/chengxuyuan_110/article/details/81109249
今日推荐