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

Django添加Project模型后migrate报错:django_content_type表已存在

Django迁移报错与表生成失败的解决方法

问题描述

我在项目中新增了名为Project的Model:

class Project(models.Model):
    statut_juridique=[
        ('per', 'personne physique' ),
        ('sarl', 'SARL'),
        ('sual', 'SUARL'),
        ('anony', 'SA'),
    ]
    type_du_projet = [
        ('ind', 'industrie'),
        ('agr', 'agronome'),
        ('ser', 'service'),
        ('art', 'artisanat'),
        ('com', 'commerce'),
    ]
    name = models.CharField(max_length=50)
    produit = ArrayField(
        ArrayField(
            models.CharField(max_length=20, blank=True),
            size=8,
                    ),
        size=8,
    )
    stat_jur = models.CharField(max_length=50, choices=statut_juridique)
    type_projet = models.CharField(max_length=50, choices=type_du_projet)
    Nomination = models.CharField(max_length=50)
    adresse = models.CharField(max_length=200)
    user = models.ForeignKey(User, related_name='projet', on_delete=models.CASCADE)


    def __str__(self):
        return self.name

执行python manage.py migrate命令时,出现如下错误:

Operations to perform: Apply all migrations: admin, auth,
businesplan, contenttypes, sessions Running migrations: Applying
contenttypes.0001_initial...Traceback (most recent call last): File
"/home/abdallah/projectdjango/oasis/venv/lib/python3.8/site-packages/django/db/backends/utils.py",
line 87, in _execute
return self.cursor.execute(sql) psycopg2.errors.DuplicateTable: relation "django_content_type" already exists

同时数据库中无法看到新建的Project表,请求协助解决。

解决步骤

1. 修复contenttypes迁移冲突

这个错误的核心是django_content_type表已存在,但Django的迁移系统认为它还未被应用。直接标记该迁移已完成:

python manage.py migrate --fake contenttypes

2. 生成自定义应用的迁移文件

确保你的businesplan应用已经生成对应迁移文件(如果还没生成):

python manage.py makemigrations businesplan

3. 执行自定义应用的迁移

如果之前的迁移记录有冲突,先fake已有的迁移记录,再执行实际迁移:

python manage.py migrate --fake businesplan
python manage.py migrate businesplan

4. 极端情况处理(手动建表导致冲突)

如果是之前手动在数据库创建过相关表引发冲突:

  • 先备份数据库,避免数据丢失
  • 删除数据库中冲突的表(django_content_type和businesplan_project)
  • 重新执行全量迁移:
python manage.py migrate

5. 验证结果

迁移完成后,登录数据库查看是否生成了businesplan_project表,也可以通过Django shell测试模型功能:

python manage.py shell

在shell中执行测试代码:

from businesplan.models import Project
from django.contrib.auth.models import User
# 创建一条测试数据
test_user = User.objects.first()
if test_user:
    p = Project(name="测试项目", stat_jur="per", type_projet="ind", Nomination="测试负责人", adresse="测试地址", user=test_user)
    p.save()
    print(Project.objects.all())

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 01:35:17