一、准备工作:
Windows7-64位
python 2.7
mysql version: 5.7.12
django 1.9.5
IDE开发工具:pycharm 2.7
二、设计表结构
主要涉及点:
1、表的ER图,要设计逻辑,有哪些表,每个表有哪些属性
2、models的 模型常用字段要熟练,本次使用的有:
CharField
ForeignKey
ImageField
TextField
DateTimeField
BooleanField
IntegerField
ManyToManyField
OneToOneField
##models.py
from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
# 帖子信息表
class Article(models.Model):
title = models.CharField(u"文章",max_length=255,unique=True)
category = models.ForeignKey("Category",verbose_name=u"板块")
head_img = models.ImageField(upload_to="uploads")
content = models.TextField(u"内容")
auther = models.ForeignKey("UserProfile")
publish_date = models.DateTimeField(auto_now=True)
hidden = models.BooleanField(default=True)
priority = models.IntegerField(u"优先级",default=1000)
def __unicode__(self):
return "<%s,author:%s>" %(self.title,self.auther)
#评论表
class Comment(models.Model):
article = models.ForeignKey(Article)
user = models.ForeignKey("UserProfile")
parent_comment = models.ForeignKey('self',related_name='p_comment',blank=True,null=True)
comment = models.TextField(max_length=1000)
date = models.DateTimeField(auto_now=True)
def __unicode__(self):
return "<%s,user:%s>" %(self.comment,self.user)
#点赞数表
class ThumbUp(models.Model):
article = models.ForeignKey('Article')
user = models.ForeignKey('UserProfile')
date = models.DateTimeField(auto_now=True)
def __unicode__(self):
return "<user:%s>" %(self.auther)
#板块分类表
class Category(models.Model):
name = models.CharField(max_length=64,unique=True)
admin = models.ManyToManyField('UserProfile')
def __unicode__(self):
return self.name
# 用户信息表
class UserProfile(models.Model):
user = models.OneToOneField(User)
name = models.CharField(max_length=32)
groups = models.ManyToManyField('UserGroup')
def __unicode__(self):
return self.name
# 用户组表
class UserGroup(models.Model):
name = models.CharField(max_length=64,unique=True)
def __unicode__(self):
return self.name
三、settings.py 里面加入数据库资源信息
首先自己需要在mysql里面创建一个数据库,名字叫s11bbs,然后编辑settings.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 's11bbs',
'HOST':'',
'USER':'root',
'PASSWORD':'123',
}
}
四、同步数据库
cd 到manage.py 文件所在目录
python manage.py migrate
python manage.py makemigrations
python manage.py migrate
五、注册数据库表
在admin.py里加入,就能访问django的后台管理界面了,可以自己尝试添加一些测试数据
http://127.0.0.1:8000/admin
## admin.py
from django.contrib import admin
import models
# Register your models here.
admin.site.register(models.Article,ArticleAdmin)
admin.site.register(models.Category,CategoryAdmin)
admin.site.register(models.Comment)
admin.site.register(models.ThumbUp)
admin.site.register(models.UserProfile)
admin.site.register(models.UserGroup)