一、使用pymysql时,必须加这两行(#如果使用mysql的数据库,请进行伪装 pymysql伪装为MySQLdb)
import pymysqlpymysql.install_as_MySQLdb() #如果使用mysql的数据库,请进行伪装 pymysql伪装为MySQLdb
二、编辑数据库内容 (路径:/学习/接口自动化/mjz/user/models.py)
from django.db import models # Create your models here. class Category(models.Model): name=models.CharField(verbose_name="分类名",max_length=50,unique=True) create_time=models.DateTimeField(verbose_name="创建时间",auto_now_add=True) update_time=models.DateTimeField(verbose_name="更新时间",auto_now=True) is_delete=models.BooleanField(verbose_name="删除",default=False) class Meta: db_table = ‘category‘ # ordering = [‘create_time‘] verbose_name="文章分类" verbose_name_plural=verbose_name def __str__(self): return self.name class Article(models.Model): title = models.CharField(verbose_name=‘文章标题‘,max_length=100,db_index=True) desc = models.CharField(verbose_name=‘描述‘,max_length=100,blank=True,null=True,default=‘这个文章没有描述‘) content = models.TextField(verbose_name=‘文章内容‘) img = models.ImageField(verbose_name=‘文章图片‘,upload_to=‘article_img‘,default=‘images/1.jpg‘) #需要pip install pillow recommend = models.BooleanField(verbose_name=‘是否推荐‘,default=False) category = models.ForeignKey(Category,verbose_name=‘分类‘,on_delete=models.DO_NOTHING, db_constraint=False) create_time = models.DateTimeField(verbose_name=‘创建时间‘, auto_now_add=True) update_time = models.DateTimeField(verbose_name=‘修改时间‘, auto_now=True) is_delete = models.BooleanField(verbose_name=‘是否删除‘, default=False) #models.CASCADE#guanl cascade # db_constraint 不会真正在数据库里面建立外键 class Meta: #首页 5 db_table = ‘article‘ # ordering = [‘create_time‘] verbose_name = ‘文章‘ verbose_name_plural = verbose_name def __str__(self): return self.title 三.执行数据库,创建表python manage.py makemigrationspython manage.py migrate 四、后台管理1、(创建后端管理员)python manage.py createsuperuser 创建用户名字 密码和邮箱2、在admin导入数据表:(/学习/接口自动化/mjz/user/admin.py)
from django.contrib import admin # Register your models here. from . import models admin.site.register(models.Category)admin.site.register(models.Article)
3、url配置(/学习/接口自动化/mjz/mjz/urls.py)
from django.contrib import adminfrom django.urls import pathfrom user.views import index urlpatterns = [ path(‘admin/‘, admin.site.urls), path(‘index/‘, index),]
原文地址:https://www.cnblogs.com/wangyajuanjuan/p/12113276.html
时间: 2024-10-31 18:22:26