django数据库迁移详细步骤:
1.项目目录结构
2.修改settings.py文件
# 设置数据库连接
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', # mysql.connector.django
'NAME': '数据库名',
'USER': '用户名',
'PASSWORD': '密码',
'HOST': '127.0.0.1',# 我连接的是本地的mysql
'PORT': '3306', # 默认端口,根据自己设置的端口进行设置
'OPTIONS': {
'init_command': "SET sql_mode='STRICT_TRANS_TABLES'",
},
}
}
3.给__init__.py文件中添加一段代码(首先必须安装pymysql)
import pymysql
pymysql.install_as_MySQLdb()
4.添加模型(modles.py)
# 图书分类(无限分类) class BookCategory(models.Model): CATEGORY_TYPE = ( (1, "一级类目"), (2, "二级类目"), (3, "三级类目"), (4, "四级类目"), ) name = models.CharField(default="", max_length=30, verbose_name="类别名", help_text="类别名") code = models.CharField(default="", max_length=30, verbose_name="类别code", help_text="类别code") desc = models.TextField(default="", verbose_name="类别描述", help_text="类别描述") category_type = models.CharField(max_length=100, default="", choices=CATEGORY_TYPE, verbose_name="类目级别",help_text="类目级别") parent_category = models.ForeignKey("self", null=True, blank=True, verbose_name="父类目录", on_delete=models.CASCADE) is_tab = models.BooleanField(default=False, verbose_name="是否导航", help_text="是否导航") add_time = models.DateTimeField(default=datetime.now, verbose_name="添加时间") class Mate: managed = True db_table = 'bookscategory' verbose_name = "商品类别" verbose_name_plural = verbose_name def __str__(self): return self.name
# 图书详情 class Books(models.Model): category = models.ForeignKey(BookCategory, null=True, blank=True, verbose_name="商品类目", on_delete=models.CASCADE) goods_sn = models.CharField(max_length=50, default="", verbose_name="图书唯一货号") name = models.CharField(max_length=300, verbose_name="图书名称") click_num = models.IntegerField(default=0, verbose_name="点击数") sold_num = models.IntegerField(default=0, verbose_name="图书销售量") fav_num = models.IntegerField(default=0, verbose_name="收藏数") goods_num = models.IntegerField(default=0, verbose_name="库存数") market_price = models.FloatField(default=0, verbose_name="市场价格") shop_price = models.FloatField(default=0, verbose_name="本店价格") goods_brief = models.TextField(max_length=500, verbose_name="图书简短描述") ship_free = models.BooleanField(default=True, verbose_name="是否承担运费") goods_front_image = models.ImageField(upload_to="upload/images", null=True, blank=True, verbose_name="封面图片") is_new = models.BooleanField(default=False, verbose_name="是否为新品") is_hot = models.BooleanField(default=False, verbose_name="是否为热销") add_time = models.DateTimeField(default=datetime.now, verbose_name="添加时间") class Mate: managed = True db_table = 'books' verbose_name = "商品详细" verbose_name_plural = verbose_name def __str__(self): return self.name
5.执行命令(确保MySQL服务开启,注意执行顺序)
python manage.py makemigrations
python manage.py migrate