You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django中makemigrations未生效,如何正确迁移自定义模型?

问题原因与解决方案

你的问题核心是模型字段定义语法错误,Django无法识别用类型注解(:)声明的字段,只会生成默认的id主键字段。

错误点分析

你在Destination模型中使用了类型注解语法(如name: models.CharField(max_length=100)),但Django要求必须用**赋值语法(=)**来定义模型字段,同时像TextField、IntegerField这类字段类需要实例化(添加())。

修正后的models.py代码

from django.db import models

# Create your models here.
class Destination(models.Model):
    name = models.CharField(max_length=100)
    img = models.ImageField(upload_to='pics')
    desc = models.TextField()
    price = models.IntegerField()
    offer = models.BooleanField(default=False)

正确执行迁移的步骤

  1. 删除项目中已有的migrations文件夹(若存在__init__.py可保留)和所有__pycache__目录
  2. 运行命令生成新的迁移文件:
    python manage.py makemigrations
    
  3. 应用迁移到数据库:
    python manage.py migrate
    

额外注意事项

  • 确保你的app已添加到settings.py的INSTALLED_APPS列表中
  • 使用ImageField需要先安装Pillow库:
    pip install pillow
    

内容的提问来源于stack exchange,提问作者Van Phong

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 22:05:56