我试图使用makemigrations命令在现有的应用程序中创建迁移,但它输出“未检测到更改”。

通常我使用startapp命令创建新的应用程序,但在创建这个应用程序时没有使用它。

调试后,我发现它没有创建迁移,因为迁移包/文件夹从应用程序中丢失。

如果文件夹不存在或者我遗漏了什么,如果它创建文件夹会更好吗?


当前回答

要为应用程序创建初始迁移,请运行makemigrations并指定应用程序名称。迁移文件夹将被创建。

./manage.py makemigrations <myapp>

你的应用必须首先包含在INSTALLED_APPS中(在settings.py内部)。

其他回答

试着在admin.py中注册你的模型,这里有一个例子:- admin.site.register (YourModelHere)

您可以做以下事情:- 1. admin.site.register(YourModelHere) # 2. 重新加载页面并重试 3.点击CTRL-S并保存 4. 可能有错误,特别检查models.py和admin.py 5. 或者,在结束时重新启动服务器

当向django api应用程序添加新模型并运行python manage.py makemigrations时,工具没有检测到任何新模型。

奇怪的是,旧模型确实被makemigrations选中了,但这是因为它们在urlpatterns链中被引用,而工具以某种方式检测到了它们。所以要注意这种行为。

这个问题是因为与models包对应的目录结构有子包,并且所有__init__.py文件都是空的。它们必须显式地在每个子文件夹和__init__.py模型中导入所有必需的类,以便Django使用makemigrationations工具来获取它们。

models
  ├── __init__.py          <--- empty
  ├── patient
  │   ├── __init__.py      <--- empty
  │   ├── breed.py
  │   └── ...
  ├── timeline
  │   ├── __init__.py      <-- empty
  │   ├── event.py
  │   └── ...

我这样解决了这个问题:

Erase the "db.sqlite3" file. The issue here is that your current data base will be erased, so you will have to remake it again. Inside the migrations folder of your edited app, erase the last updated file. Remember that the first created file is: "0001_initial.py". For example: I made a new class and register it by the "makemigrations" and "migrate" procedure, now a new file called "0002_auto_etc.py" was created; erase it. Go to the "pycache" folder (inside the migrations folder) and erase the file "0002_auto_etc.pyc". Finally, go to the console and use "python manage.py makemigrations" and "python manage.py migrate".

还有一个非常愚蠢的问题是在模型中定义两个类Meta。在这种情况下,在运行makemigrations时,对第一个的任何更改都不会应用。

class Product(models.Model):
    somefield = models.CharField(max_length=255)
    someotherfield = models.CharField(max_length=255)

    class Meta:
        indexes = [models.Index(fields=["somefield"], name="somefield_idx")]

    def somefunc(self):
        pass

    # Many lines...

    class Meta:
        indexes = [models.Index(fields=["someotherfield"], name="someotherfield_idx")]

更新:在尝试之前,应该确保migrations文件夹中存在__init__.py文件:

./manage.py makemigrations <myapp1> <myapp2>…< myappN >


有时。/manage.py makemigrations优于。/manage.py makemigrations <myapp>,因为它可以处理应用程序之间的某些冲突。

这些情况都是悄无声息地发生的,需要几个小时的咒骂才能理解可怕的“检测到没有变化”消息的真正含义。

因此,使用下面的命令是一个更好的选择:

./manage.py makemigrations <myapp1> <myapp2>…< myappN >