标签归档:django-migrations

Django-makemigrations-未检测到更改

问题:Django-makemigrations-未检测到更改

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

通常,我使用startapp命令创建新应用,但在创建该应用时并未将其用于该应用。

调试后,我发现它没有创建迁移,因为migrations应用程序中缺少软件包/文件夹。

如果不存在该文件夹,还是创建丢失的文件夹,会更好吗?

I was trying to create migrations within an existing app using the makemigrations command but it outputs “No changes detected”.

Usually I create new apps using the startapp command but did not use it for this app when I created it.

After debugging, I found that it is not creating migration because the migrations package/folder is missing from an app.

Would it be better if it creates the folder if it is not there or am I missing something?


回答 0

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

./manage.py makemigrations <myapp>

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

To create initial migrations for an app, run makemigrations and specify the app name. The migrations folder will be created.

./manage.py makemigrations <myapp>

Your app must be included in INSTALLED_APPS first (inside settings.py).


回答 1

我的问题(以及解决方案)与上述问题有所不同。

我没有使用models.py文件,而是创建了一个models目录并在my_model.py其中创建了文件,并在其中放置了模型。Django找不到我的模型,因此它写道没有要应用的迁移。

我的解决方案是:在my_app/models/__init__.py文件中添加以下行: from .my_model import MyModel

My problem (and so solution) was yet different from those described above.

I wasn’t using models.py file, but created a models directory and created the my_model.py file there, where I put my model. Django couldn’t find my model so it wrote that there are no migrations to apply.

My solution was: in the my_app/models/__init__.py file I added this line: from .my_model import MyModel


回答 2

django在makemigrations命令执行期间未检测到要迁移的内容有多种可能的原因。

  1. 迁移文件夹您的应用程序中需要一个迁移软件包。
  2. INSTALLED_APPS您需要在INSTALLED_APPS.dict中指定您的应用
  3. 详尽度 从运行makemigrations -v 3冗长开始。这可能会为这个问题提供一些启示。
  4. 完整路径INSTALLED_APPS建议指定完整的模块应用程序配置路径“apply.apps.MyAppConfig”
  5. –settings,您可能需要确保设置了正确的设置文件:manage.py makemigrations --settings mysite.settings
  6. 指定应用程序名称可以显式地放入应用程序名称manage.py makemigrations myapp-不仅可以缩小应用程序的迁移范围,而且可以帮助您隔离问题。
  7. 模型元检查你有合适的app_label模型中的元

  8. 调试django调试django核心脚本。makemigrations命令非常简单。这是在pycharm中执行的方法。相应地改变你的脚本定义(例如:makemigrations --traceback myapp

多个数据库:

  • DB路由器时使用Django DB路由器,路由器类(您的自定义类路由器)工作需要实现的allow_syncdb方法。

makemigrations总是为模型更改创建迁移,但是如果allow_migrate()返回False,

There are multiple possible reasons for django not detecting what to migrate during the makemigrations command.

  1. migration folder You need a migrations package in your app.
  2. INSTALLED_APPS You need your app to be specified in the INSTALLED_APPS .dict
  3. Verbosity start by running makemigrations -v 3 for verbosity. This might shed some light on the problem.
  4. Full path In INSTALLED_APPS it is recommended to specify the full module app config path ‘apply.apps.MyAppConfig’
  5. –settings you might want to make sure the correct settings file is set: manage.py makemigrations --settings mysite.settings
  6. specify app name explicitly put the app name in manage.py makemigrations myapp – that narrows down the migrations for the app alone and helps you isolate the problem.
  7. model meta check you have the right app_label in your model meta

  8. Debug django debug django core script. makemigrations command is pretty much straight forward. Here’s how to do it in pycharm. change your script definition accordingly (ex: makemigrations --traceback myapp)

Multiple databases:

  • Db Router when working with django db router, the router class (your custom router class) needs to implement the allow_syncdb method.

makemigrations always creates migrations for model changes, but if allow_migrate() returns False,


回答 3

我已经读过许多关于这个问题的答案,通常说它们只是makemigrations以其他方式运行。但是对我来说,问题出在Meta模型的子类中。

我有一个应用程序配置说label = <app name>(在apps.py文件中models.pyviews.py等等)。如果您的元类碰巧没有与应用程序标签相同的标签(例如,因为您将一个太大的应用程序拆分为多个应用程序),则不会检测到任何更改(也不会显示任何有用的错误消息)。因此,在我的模型课中,我现在有:

class ModelClassName(models.Model):

    class Meta:
        app_label = '<app name>' # <-- this label was wrong before.

    field_name = models.FloatField()
    ...

在此处运行Django 1.10。

I’ve read many answers to this question often stating to simply run makemigrations in some other ways. But to me, the problem was in the Meta subclass of models.

I have an app config that says label = <app name> (in the apps.py file, beside models.py, views.py etc). If by any chance your meta class doesn’t have the same label as the app label (for instance because you are splitting one too big app into multiple ones), no changes are detected (and no helpful error message whatsoever). So in my model class I have now:

class ModelClassName(models.Model):

    class Meta:
        app_label = '<app name>' # <-- this label was wrong before.

    field_name = models.FloatField()
    ...

Running Django 1.10 here.


回答 4

这是一个评论,但可能应该是一个答案。

确保您的应用程序名称位于settings.py中,INSTALLED_APPS否则无论执行什么操作都不会运行迁移。

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    'blog',
]

然后运行:

./manage.py makemigrations blog

It is a comment but should probably be an answer.

Make sure that your app name is in settings.py INSTALLED_APPS otherwise no matter what you do it will not run the migrations.

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    'blog',
]

Then run:

./manage.py makemigrations blog

回答 5

我还有另一个这里未描述的问题,这让我发疯。

class MyModel(models.Model):
    name = models.CharField(max_length=64, null=True)  # works
    language_code = models.CharField(max_length=2, default='en')  # works
    is_dumb = models.BooleanField(default=False),  # doesn't work

在复制和粘贴的一行中,我有一个尾随的“,”。is_dumb所在的行不会使用’./manage.py makemigrations’创建模型迁移,但也不会引发错误。删除“后,”它按预期方式工作。

因此,在复制粘贴时请多加注意:-)

I had another problem not described here, which drove me nuts.

class MyModel(models.Model):
    name = models.CharField(max_length=64, null=True)  # works
    language_code = models.CharField(max_length=2, default='en')  # works
    is_dumb = models.BooleanField(default=False),  # doesn't work

I had a trailing ‘,’ in one line perhaps from copy&paste. The line with is_dumb doesn’t created a model migration with ‘./manage.py makemigrations’ but also didn’t throw an error. After removing the ‘,’ it worked as expected.

So be careful when you do copy&paste :-)


回答 6

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

这些场合默默发生,花了几个小时swearing才能理解恐惧的真正含义No changes detected消息。

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

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

There are sometimes when ./manage.py makemigrations is superior to ./manage.py makemigrations <myapp> because it can handle certain conflicts between apps.

Those occasions occur silently and it takes several hours of swearing to understand the real meaning of the dreaded No changes detected message.

Therefore, it is a far better choice to make use of the following command:

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


回答 7

我从django外部复制了一个表,默认将Meta类设置为“ managed = false”。例如:

class Rssemailsubscription(models.Model):
    id = models.CharField(primary_key=True, max_length=36)
    ...
    area = models.FloatField('Area (Sq. KM)', null=True)

    class Meta:
        managed = False
        db_table = 'RSSEmailSubscription'

通过将managed更改为True,makemigrations开始接受更改。

I had copied a table in from outside of django and the Meta class defaulted to “managed = false”. For example:

class Rssemailsubscription(models.Model):
    id = models.CharField(primary_key=True, max_length=36)
    ...
    area = models.FloatField('Area (Sq. KM)', null=True)

    class Meta:
        managed = False
        db_table = 'RSSEmailSubscription'

By changing manged to True, makemigrations started picking up changes.


回答 8

  1. 确保您的应用在settings.py中的installed_apps中被提及
  2. 确保您的模型类扩展了模型。
  1. Make sure your app is mentioned in installed_apps in settings.py
  2. Make sure you model class extends models.Model

回答 9

我这样做来解决了这个问题:

  1. 擦除“ db.sqlite3”文件。这里的问题是您当前的数据库将被删除,因此您将不得不重新制作它。
  2. 在已编辑的应用程序的迁移文件夹中,删除上次更新的文件。请记住,第一个创建的文件是:“ 0001_initial.py”。例如:我创建了一个新类,并通过“ makemigrations”和“ migrate”过程进行了注册,现在创建了一个名为“ 0002_auto_etc.py”的新文件;删除它。
  3. 转到pycache ”文件夹(位于migrations文件夹内),然后删除文件“ 0002_auto_etc.pyc”。
  4. 最后,转到控制台并使用“ python manage.py makemigrations”和“ python manage.py migration”。

I solved that problem by doing this:

  1. 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.
  2. 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.
  3. Go to the “pycache” folder (inside the migrations folder) and erase the file “0002_auto_etc.pyc”.
  4. Finally, go to the console and use “python manage.py makemigrations” and “python manage.py migrate”.

回答 10

我忘了提出正确的论点:

class LineInOffice(models.Model):   # here
    addressOfOffice = models.CharField("Корхоная жош",max_length= 200)   #and here
    ...

在models.py中,然后就开始消除烦人的

在应用程序“ myApp”中未检测到更改

I forgot to put correct arguments:

class LineInOffice(models.Model):   # here
    addressOfOffice = models.CharField("Корхоная жош",max_length= 200)   #and here
    ...

in models.py and then it started to drop that annoying

No changes detected in app ‘myApp ‘


回答 11

另一个可能的原因是,如果您在其他文件中(而不是在程序包中)定义了某些模型,而在其他任何地方都没有引用过。

对我来说,简单地增加from .graph_model import *,以admin.py(其中graph_model.py为新文件)解决了这一问题。

Another possible reason is if you had some models defined in another file (not in a package) and haven’t referenced that anywhere else.

For me, simply adding from .graph_model import * to admin.py (where graph_model.py was the new file) fixed the problem.


回答 12

我的问题比上面的答案要简单得多,并且可能是一个更普遍的原因,只要您的项目已经建立并可以运行。在我的一个已经使用了很长时间的应用程序中,迁移似乎很困难,因此,我急着做了以下事情:

rm -r */migrations/*
rm db.sqlite3
python3 manage.py makemigrations
No changes detected

哇?

我错误地还删除了所有__init__.py文件:(-进入后,一切又恢复正常了:

touch ads1/migrations/__init__.py

对于我的每个应用程序,都可以makemigrations再次使用。

事实证明,我已经手动通过复制另一个创建了一个新的应用程序,忘了把__init__.pymigrations文件夹和confinved我,一切都是靠不住的-我的领先使得它与更坏rm -r如上所述。

希望这可以帮助某人在几个小时内发誓“未检测到更改”错误。

My problem was much simpler than the above answers and probably a far more common reason as long as your project is already set up and working. In one of my applications that had been working for a long time, migrations seemed wonky, so in a hurry, I did the following:

rm -r */migrations/*
rm db.sqlite3
python3 manage.py makemigrations
No changes detected

Whaat??

I had mistakenly also removed all the __init__.py files :( – Everything was working again after I went in and:

touch ads1/migrations/__init__.py

For each of my applications then the makemigrations worked again.

It turns out that I had manually created a new application by copying another and forgot to put the __init__.py in the migrations folder and that confinved me that everything was wonky – leading my making it worse with an rm -r as described above.

Hope this helps someone from swearing at the “No changes detected” error for a few hours.


回答 13

解决方案是您必须将您的应用程序包含在INSTALLED_APPS中。

我错过了,发现了同样的问题。

指定我的应用名称后,迁移成功

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'boards',
]

请注意,我最后提到的木板是我的应用名称。

The solution is you have to include your app in INSTALLED_APPS.

I missed it and I found this same issue.

after specifying my app name migration became successful

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'boards',
]

please note I mentioned boards in last, which is my app name.


回答 14

INSTALLED_APPS = [

'blog.apps.BlogConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',

]

确保“ blog.apps.BlogConfig”(此设置包含在settings.py中,以便进行应用迁移)

然后运行python3 manage.py makemigrations博客或您的应用名称

INSTALLED_APPS = [

'blog.apps.BlogConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',

]

make sure ‘blog.apps.BlogConfig’, (this is included in your settings.py in order to make your app migrations)

then run python3 manage.py makemigrations blog or your app name


回答 15

您可能还会遇到的一个非常愚蠢的问题是class 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")]

A very dumb issue you can have as well is to define two class Meta in your model. In that case, any change to the first one won’t be applied when running 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")]

回答 16

我知道这是一个老问题,但是我整天都在同一个问题上作斗争,而我的解决方案很简单。

我的目录结构类似于…

apps/
   app/
      __init__.py
      app_sub1/
           __init__.py
           models.py
      app_sub2/
           __init__.py
           models.py
      app_sub3/
           __init__.py
           models.py
   app2/
      __init__.py
      app2_sub1/
           __init__.py
           models.py
      app2_sub2/
           __init__.py
           models.py
      app2_sub3/
           __init__.py
           models.py
    main_app/
      __init__.py
      models.py

而且由于直到我遇到问题的所有其他模型都被导入到其他地方,最后又从main_app那里导入了INSTALLED_APPS,所以我很幸运,他们都可以使用。

但是由于我只添加了一个appINSTALLED_APPS而不是app_sub*当我最终添加了一个其他未导入的新模型文件时添加的,因此Django完全忽略了它。

我的解决方法是像这样将models.py文件添加到每个文件的基本目录中app

apps/
   app/
      __init__.py
      models.py <<<<<<<<<<--------------------------
      app_sub1/
           __init__.py
           models.py
      app_sub2/
           __init__.py
           models.py
      app_sub3/
           __init__.py
           models.py
   app2/
      __init__.py
      models.py <<<<<<<<<<--------------------------
      app2_sub1/
           __init__.py
           models.py
      app2_sub2/
           __init__.py
           models.py
      app2_sub3/
           __init__.py
           models.py
    main_app/
      __init__.py
      models.py

然后添加from apps.app.app_sub1 import *等等到每个app关卡models.py文件中。

Bleh …这花了我很长时间才弄清楚,我在任何地方都找不到解决方案…我什至转到了Google搜索结果的第2页。

希望这对某人有帮助!

I know this is an old question but I fought with this same issue all day and my solution was a simple one.

I had my directory structure something along the lines of…

apps/
   app/
      __init__.py
      app_sub1/
           __init__.py
           models.py
      app_sub2/
           __init__.py
           models.py
      app_sub3/
           __init__.py
           models.py
   app2/
      __init__.py
      app2_sub1/
           __init__.py
           models.py
      app2_sub2/
           __init__.py
           models.py
      app2_sub3/
           __init__.py
           models.py
    main_app/
      __init__.py
      models.py

And since all the other models up until the one I had a problem with were being imported somewhere else that ended up importing from main_app which was registered in the INSTALLED_APPS, I just got lucky that they all worked.

But since I only added each app to INSTALLED_APPS and not the app_sub* when I finally added a new models file that wasn’t imported ANYWHERE else, Django totally ignored it.

My fix was adding a models.py file to the base directory of each app like this…

apps/
   app/
      __init__.py
      models.py <<<<<<<<<<--------------------------
      app_sub1/
           __init__.py
           models.py
      app_sub2/
           __init__.py
           models.py
      app_sub3/
           __init__.py
           models.py
   app2/
      __init__.py
      models.py <<<<<<<<<<--------------------------
      app2_sub1/
           __init__.py
           models.py
      app2_sub2/
           __init__.py
           models.py
      app2_sub3/
           __init__.py
           models.py
    main_app/
      __init__.py
      models.py

and then add from apps.app.app_sub1 import * and so on to each of the app level models.py files.

Bleh… this took me SO long to figure out and I couldn’t find the solution anywhere… I even went to page 2 of the google results.

Hope this helps someone!


回答 17

根据官方文档中的“迁移”部分,我在django 3.0中遇到了类似的问题,运行它足以更新我的表结构:

python manage.py makemigrations
python manage.py migrate

但是输出始终是相同的:执行“ makemigrations”脚本后,模型“未检测到更改”。我要在数据库上更新的模型在models.py上出现语法错误:

field_model : models.CharField(max_length=255, ...)

代替:

field_model = models.CharField(max_length=255, ...)

解决了这个愚蠢的错误,使用这些命令可以顺利进行迁移。也许这可以帮助某人。

I had a similar issue with django 3.0, according migrations section in the official documentation, running this was enough to update my table structure:

python manage.py makemigrations
python manage.py migrate

But the output was always the same: ‘no change detected’ about my models after I executed ‘makemigrations’ script. I had a syntax error on models.py at the model I wanted to update on db:

field_model : models.CharField(max_length=255, ...)

instead of:

field_model = models.CharField(max_length=255, ...)

Solving this stupid mistake, with those command the migration was done without problems. Maybe this helps someone.


回答 18

您应该添加polls.apps.PollsConfigINSTALLED_APPSsetting.py

You should add polls.apps.PollsConfig to INSTALLED_APPS in setting.py


回答 19

就我而言,我忘记插入类参数

错误:

class AccountInformation():

正确

class AccountInformation(models.Model):

In my case i forgot to insert the class arguments

Wrong:

class AccountInformation():

Correct

class AccountInformation(models.Model):

回答 20

就我而言,我首先向模型添加了一个字段,而Django说没有任何变化。

比起我决定更改模型的“表名”,makemigrations起作用了。比起将表名改回默认值,新字段也在那里。

django迁移系统中有一个“ bug”,有时看不到新字段。可能与日期字段有关。

In my case, I first added a field to the model, and Django said there’re no changes.

Than I decided to change the “table name” of the model, makemigrations worked. Than I changed table name back to default, and the new field was also there.

There is a “bug” in django migration system, sometimes it doesn’t see the new field. Might be related with date field.


回答 21

可能的原因可能是删除了现有的db文件和migrations文件夹,您可以使用python manage.py makemigrations <app_name>来工作。我曾经遇到过类似的问题。

The possible reason could be deletion of the existing db file and migrations folder you can use python manage.py makemigrations <app_name> this should work. I once faced a similar problem.


回答 22

另一种边缘情况和解决方案:

我添加了一个布尔字段,并同时添加了一个引用该属性的@property,其名称相同(doh)。注释了该属性,并且迁移看到并添加了新字段。重命名该属性,一切都很好。

One more edge case and solution:

I added a boolean field, and at the same time added an @property referencing it, with the same name (doh). Commented the property and migration sees and adds the new field. Renamed the property and all is good.


回答 23

如果您拥有managed = True模型内部元数据,则需要将其删除并进行迁移。然后再次运行迁移,它将检测到新更新。

If you have the managed = True in yout model Meta, you need to remove it and do a migration. Then run the migrations again, it will detect the new updates.


回答 24

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

奇怪的是,旧模型确实被选中了makemigrations,但这是因为它们在urlpatterns链中并且该工具以某种方式检测到了它们。因此,请注意该行为。

问题是因为与models包相对应的目录结构具有子包,并且所有__init__.py文件均为空。他们必须在每个子文件夹和模型中 显式导入所有必需的类,以__init__.py供Django使用该makemigrations工具将其提取。

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

When adding new models to the django api application and running the python manage.py makemigrations the tool did not detect any new models.

The strange thing was that the old models did got picked by makemigrations, but this was because they were referenced in the urlpatterns chain and the tool somehow detected them. So keep an eye on that behavior.

The problem was because the directory structure corresponding to the models package had subpackages and all the __init__.py files were empty. They must explicitly import all the required classes in each subfolder and in the models __init__.py for Django to pick them up with the makemigrations tool.

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

回答 25

尝试在admin.py中注册模型,这是一个示例:-admin.site.register(YourModelHere)

您可以执行以下操作:1. 1. admin.site.register(YourModelHere)#在admin.py中2.重新加载页面并重试3.按下CTRL-S并保存4.可能有错误,特别是检查模型.py和admin.py5。或者,在结束时,只需重新启动服务器即可。

Try registering your model in admin.py, here’s an example:- admin.site.register(YourModelHere)

You can do the following things:- 1. admin.site.register(YourModelHere) # In admin.py 2. Reload the page and try again 3. Hit CTRL-S and save 4. There might be an error, specially check models.py and admin.py 5. Or, at the end of it all just restart the server


回答 26

这可能希望对其他人有所帮助,因为我最终花了数小时试图将其消除。

如果你有一个函数模型由同一个名字,这将删除值。事后看来很明显,但仍然如此。

因此,如果您有这样的事情:

class Foobar(models.Model):
    [...]
    something = models.BooleanField(default=False)

    [...]
    def something(self):
        return [some logic]

在这种情况下,该功能将覆盖上面的设置,使其对变为“不可见” makemigrations

This might hopefully help someone else, as I ended up spending hours trying to chase this down.

If you have a function within your model by the same name, this will remove the value. Pretty obvious in hindsight, but nonetheless.

So, if you have something like this:

class Foobar(models.Model):
    [...]
    something = models.BooleanField(default=False)

    [...]
    def something(self):
        return [some logic]

In that case, the function will override the setting above, making it “invisible” to makemigrations.


回答 27

您可以做的最好的事情是,删除现有数据库。就我而言,我使用的是phpMyAdmin SQL数据库,因此我手动删除了上面创建的数据库。

删除后: 我在PhpMyAdmin中创建数据库,并且不添加任何表。

再次运行以下命令:

python manage.py makemigrations

python manage.py migrate

这些命令之后:您可以看到django在数据库中自动创建了其他必要的表(大约有10个表)。

python manage.py makemigrations <app_name>

python manage.py migrate

最后:在上述命令之后,您创建的所有模型(表)都将直接导入数据库。

希望这会有所帮助。

The Best Thing You can do is, Delete the existing database. In my case, I were using phpMyAdmin SQL database, so I manually delete the created database overthere.

After Deleting: I create database in PhpMyAdmin, and doesn,t add any tables.

Again run the following Commands:

python manage.py makemigrations

python manage.py migrate

After These Commands: You can see django has automatically created other necessary tables in Database(Approx there are 10 tables).

python manage.py makemigrations <app_name>

python manage.py migrate

And Lastly: After above commands all the model(table) you have created are directly imported to the database.

Hope this will help.


回答 28

我对此错误的问题是,我包括了:

class Meta:
   abstract = True

我要为其创建的内部模型。

My problem with this error, was that I had included:

class Meta:
   abstract = True

Inside model that I wanted to creation migrate for.


回答 29

创建一个名为的新应用时,我遇到了另一个问题deals。我想在该应用中分离模型,所以我有2个名为deals.py和的模型文件dealers.py。运行时,python manage.py makemigrations我得到了:No changes detected

我继续前进,并将__init__.py其放在我的模型文件所在的同一目录(交易和经销商)中

from .deals import *
from .dealers import *

然后makemigrations命令起作用了。

原来,如果您不打算在任何地方导入模型,或者模型文件名不是 models.py不会检测到模型。

我遇到的另一个问题是我在settings.py以下位置编写应用程序的方式:

我有:

apps.deals

它应该已经包含了根项目文件夹:

cars.apps.deals

I had a different issue while creating a new app called deals. I wanted to separate the models inside that app so I had 2 model files named deals.py and dealers.py. When running python manage.py makemigrations I got: No changes detected.

I went ahead and inside the __init__.py which lives on the same directory where my model files lived (deals and dealer) I did

from .deals import *
from .dealers import *

And then the makemigrations command worked.

Turns out that if you are not importing the models anywhere OR your models file name isn’t models.py then the models wont be detected.

Another issue that happened to me is the way I wrote the app in settings.py:

I had:

apps.deals

It should’ve been including the root project folder:

cars.apps.deals

Django-DB-Migrations:无法更改表,因为它具有未决的触发事件

问题:Django-DB-Migrations:无法更改表,因为它具有未决的触发事件

我想从TextField中删除null = True:

-    footer=models.TextField(null=True, blank=True)
+    footer=models.TextField(blank=True, default='')

我创建了一个架构迁移:

manage.py schemamigration fooapp --auto

由于某些页脚列包含,NULL因此error在运行迁移时会得到以下信息:

django.db.utils.IntegrityError:“页脚”列包含空值

我将其添加到架构迁移中:

    for sender in orm['fooapp.EmailSender'].objects.filter(footer=None):
        sender.footer=''
        sender.save()

现在我得到:

django.db.utils.DatabaseError: cannot ALTER TABLE "fooapp_emailsender" because it has pending trigger events

怎么了?

I want to remove null=True from a TextField:

-    footer=models.TextField(null=True, blank=True)
+    footer=models.TextField(blank=True, default='')

I created a schema migration:

manage.py schemamigration fooapp --auto

Since some footer columns contain NULL I get this error if I run the migration:

django.db.utils.IntegrityError: column “footer” contains null values

I added this to the schema migration:

    for sender in orm['fooapp.EmailSender'].objects.filter(footer=None):
        sender.footer=''
        sender.save()

Now I get:

django.db.utils.DatabaseError: cannot ALTER TABLE "fooapp_emailsender" because it has pending trigger events

What is wrong?


回答 0

造成这种情况的另一个原因可能是因为您尝试将一列设置为NOT NULL实际上已经具有NULL值的时间。

Another reason for this maybe because you try to set a column to NOT NULL when it actually already has NULL values.


回答 1

每次迁移都在事务内部。在PostgreSQL中,您不得在一个事务中更新表然后更改表模式。

您需要拆分数据迁移和架构迁移。首先使用以下代码创建数据迁移:

 for sender in orm['fooapp.EmailSender'].objects.filter(footer=None):
    sender.footer=''
    sender.save()

然后创建架构迁移:

manage.py schemamigration fooapp --auto

现在,您有两个事务,并且应该在两个步骤中进行迁移。

Every migration is inside a transaction. In PostgreSQL you must not update the table and then alter the table schema in one transaction.

You need to split the data migration and the schema migration. First create the data migration with this code:

 for sender in orm['fooapp.EmailSender'].objects.filter(footer=None):
    sender.footer=''
    sender.save()

Then create the schema migration:

manage.py schemamigration fooapp --auto

Now you have two transactions and the migration in two steps should work.


回答 2

刚刚遇到这个问题。您还可以在模式迁移中使用db.start_transaction()和db.commit_transaction()将数据更改与模式更改分开。可能不那么干净,无法进行单独的数据迁移,但是在我的情况下,我需要架构,数据,然后再进行另一种架构迁移,因此我决定一次完成所有操作。

Have just hit this problem. You can also use db.start_transaction() and db.commit_transaction() in the schema migration to separate data changes from schema changes. Probably not so clean as to have a separate data migration but in my case I would need schema, data, and then another schema migration so I decided to do it all at once.


回答 3

在操作中,我将SET约束:

operations = [
    migrations.RunSQL('SET CONSTRAINTS ALL IMMEDIATE;'),
    migrations.RunPython(migration_func),
    migrations.RunSQL('SET CONSTRAINTS ALL DEFERRED;'),
]

At the operations I put SET CONSTRAINTS:

operations = [
    migrations.RunSQL('SET CONSTRAINTS ALL IMMEDIATE;'),
    migrations.RunPython(migration_func),
    migrations.RunSQL('SET CONSTRAINTS ALL DEFERRED;'),
]

回答 4

您正在更改列架构。该页脚列不能再包含空白值。该列中很可能已经有空白值存储在数据库中。Django将使用migration命令将数据库中的空白行从空白更新为现在的默认值。Django尝试更新页脚列为空值的行,并在看起来相同的同时更改架构(我不确定)。

问题是您无法更改试图同时更新其值的列模式。

一种解决方案是删除迁移文件以更新架构。然后,运行脚本以将所有这些值更新为默认值。然后重新运行迁移以更新架构。这样,更新已完成。Django迁移仅更改架构。

You are altering the column schema. That footer column can no longer contain a blank value. There are most likely blank values already stored in the DB for that column. Django is going to update those blank rows in your DB from blank to the now default value with the migrate command. Django tries to update the rows where footer column has a blank value and change the schema at the same time it seems (I’m not sure).

The problem is you can’t alter the same column schema you are trying to update the values for at the same time.

One solution would be to delete the migrations file updating the schema. Then, run a script to update all those values to your default value. Then re-run the migration to update the schema. This way, the update is already done. Django migration is only altering the schema.


如何从Django 1.7的初始迁移迁移回去?

问题:如何从Django 1.7的初始迁移迁移回去?

我用一些模型创建了一个新的应用程序,现在我发现一些模型没有经过深思熟虑。由于我尚未提交代码,因此明智的做法是将数据库迁移到最后的良好状态,并使用更好的模型重新进行迁移。在这种情况下,最后的良好状态是新应用程序不存在的数据库。

如何从Django 1.7的初始迁移迁移回去?

South一个可以这样做:

python manage.py migrate <app> zero

<app>将从迁移历史记录中清除并删除的所有表<app>

如何在Django 1.7迁移中做到这一点?

I created a new app with some models and now I noticed that some of the models are poorly thought out. As I haven’t committed the code the sensible thing would be to migrate the database to last good state and redo the migration with better models. In this case the last good state is database where the new app doesn’t exist.

How can I migrate back from initial migration in Django 1.7?

In South one could do:

python manage.py migrate <app> zero

Which would clear <app> from migration history and drop all tables of <app>.

How to do this with Django 1.7 migrations?


回答 0

您也可以使用Django 1.7+进行相同操作:

python manage.py migrate <app> zero

<app>将从迁移历史记录中清除,并删除所有的表<app>

有关更多信息,请参见django文档

You can do the same with Django 1.7+ also:

python manage.py migrate <app> zero

This clears <app> from migration history and drops all tables of <app>

See django docs for more info.


回答 1

您还可以使用版本号:

python manage.py migrate <app> 0002

来源:https : //docs.djangoproject.com/en/1.7/ref/django-admin/#django-admin-migrate

you can also use the version number:

python manage.py migrate <app> 0002

Source: https://docs.djangoproject.com/en/1.7/ref/django-admin/#django-admin-migrate


用于重命名模型和关系字段的Django迁移策略

问题:用于重命名模型和关系字段的Django迁移策略

我打算重命名现有Django项目中的多个模型,在该项目中,还有许多其他模型与我要重命名的模型具有外键关系。我相当确定这将需要多次迁移,但是我不确定确切的过程。

假设我从Django应用程序中的以下模型开始myapp

class Foo(models.Model):
    name = models.CharField(unique=True, max_length=32)
    description = models.TextField(null=True, blank=True)


class AnotherModel(models.Model):
    foo = models.ForeignKey(Foo)
    is_awesome = models.BooleanField()


class YetAnotherModel(models.Model):
    foo = models.ForeignKey(Foo)
    is_ridonkulous = models.BooleanField()

我想重命名该Foo模型,因为该名称实际上没有意义,并且会导致代码混乱,并且Bar会使名称更清晰。

根据我在Django开发文档中阅读的内容,我假设采用以下迁移策略:

第1步

修改models.py

class Bar(models.Model):  # <-- changed model name
    name = models.CharField(unique=True, max_length=32)
    description = models.TextField(null=True, blank=True)


class AnotherModel(models.Model):
    foo = models.ForeignKey(Bar)  # <-- changed relation, but not field name
    is_awesome = models.BooleanField()


class YetAnotherModel(models.Model):
    foo = models.ForeignKey(Bar)  # <-- changed relation, but not field name
    is_ridonkulous = models.BooleanField()

注意,的AnotherModel字段名称foo没有更改,但是关系已更新为Bar模型。我的理由是,我不应一次更改太多,并且如果将该字段名称更改为,则bar可能会丢失该列中的数据。

第2步

创建一个空迁移:

python manage.py makemigrations --empty myapp

第三步

编辑Migration在步骤2中创建的迁移文件中的类,RenameModel以将该操作添加到操作列表中:

class Migration(migrations.Migration):

    dependencies = [
        ('myapp', '0001_initial'),
    ]

    operations = [
        migrations.RenameModel('Foo', 'Bar')
    ]

第4步

应用迁移:

python manage.py migrate

第5步

在中编辑相关字段名称models.py

class Bar(models.Model):
    name = models.CharField(unique=True, max_length=32)
    description = models.TextField(null=True, blank=True)


class AnotherModel(models.Model):
    bar = models.ForeignKey(Bar)  # <-- changed field name
    is_awesome = models.BooleanField()


class YetAnotherModel(models.Model):
    bar = models.ForeignKey(Bar)  # <-- changed field name
    is_ridonkulous = models.BooleanField()

第6步

创建另一个空迁移:

python manage.py makemigrations --empty myapp

步骤7

编辑Migration在步骤6中创建的迁移文件中的类,以将RenameField任何相关字段名称的操作添加到操作列表中:

class Migration(migrations.Migration):

    dependencies = [
        ('myapp', '0002_rename_fields'),  # <-- is this okay?
    ]

    operations = [
        migrations.RenameField('AnotherModel', 'foo', 'bar'),
        migrations.RenameField('YetAnotherModel', 'foo', 'bar')
    ]

步骤8

应用第二次迁移:

python manage.py migrate

除了更新其余代码(视图,表单等)以反映新的变量名之外,这基本上是新的迁移功能如何起作用的吗?

另外,这似乎需要很多步骤。迁移操作可以某种方式压缩吗?

谢谢!

I’m planning to rename several models in an existing Django project where there are many other models that have foreign key relationships to the models I would like to rename. I’m fairly certain this will require multiple migrations, but I’m not sure of the exact procedure.

Let’s say I start out with the following models within a Django app called myapp:

class Foo(models.Model):
    name = models.CharField(unique=True, max_length=32)
    description = models.TextField(null=True, blank=True)


class AnotherModel(models.Model):
    foo = models.ForeignKey(Foo)
    is_awesome = models.BooleanField()


class YetAnotherModel(models.Model):
    foo = models.ForeignKey(Foo)
    is_ridonkulous = models.BooleanField()

I want to rename the Foo model because the name doesn’t really make sense and is causing confusion in the code, and Bar would make for a much clearer name.

From what I have read in the Django development documentation, I’m assuming the following migration strategy:

Step 1

Modify models.py:

class Bar(models.Model):  # <-- changed model name
    name = models.CharField(unique=True, max_length=32)
    description = models.TextField(null=True, blank=True)


class AnotherModel(models.Model):
    foo = models.ForeignKey(Bar)  # <-- changed relation, but not field name
    is_awesome = models.BooleanField()


class YetAnotherModel(models.Model):
    foo = models.ForeignKey(Bar)  # <-- changed relation, but not field name
    is_ridonkulous = models.BooleanField()

Note the AnotherModel field name for foo doesn’t change, but the relation is updated to the Bar model. My reasoning is that I shouldn’t change too much at once and that if I changed this field name to bar I would risk losing the data in that column.

Step 2

Create an empty migration:

python manage.py makemigrations --empty myapp

Step 3

Edit the Migration class in the migration file created in step 2 to add the RenameModel operation to the operations list:

class Migration(migrations.Migration):

    dependencies = [
        ('myapp', '0001_initial'),
    ]

    operations = [
        migrations.RenameModel('Foo', 'Bar')
    ]

Step 4

Apply the migration:

python manage.py migrate

Step 5

Edit the related field names in models.py:

class Bar(models.Model):
    name = models.CharField(unique=True, max_length=32)
    description = models.TextField(null=True, blank=True)


class AnotherModel(models.Model):
    bar = models.ForeignKey(Bar)  # <-- changed field name
    is_awesome = models.BooleanField()


class YetAnotherModel(models.Model):
    bar = models.ForeignKey(Bar)  # <-- changed field name
    is_ridonkulous = models.BooleanField()

Step 6

Create another empty migration:

python manage.py makemigrations --empty myapp

Step 7

Edit the Migration class in the migration file created in step 6 to add the RenameField operation(s) for any related field names to the operations list:

class Migration(migrations.Migration):

    dependencies = [
        ('myapp', '0002_rename_fields'),  # <-- is this okay?
    ]

    operations = [
        migrations.RenameField('AnotherModel', 'foo', 'bar'),
        migrations.RenameField('YetAnotherModel', 'foo', 'bar')
    ]

Step 8

Apply the 2nd migration:

python manage.py migrate

Aside from updating the rest of the code (views, forms, etc.) to reflect the new variable names, is this basically how the new migration functionality would work?

Also, this seems like a lot of steps. Can the migration operations be condensed in some way?

Thanks!


回答 0

因此,当我尝试此操作时,您似乎可以将步骤3-7压缩:

class Migration(migrations.Migration):

    dependencies = [
        ('myapp', '0001_initial'), 
    ]

    operations = [
        migrations.RenameModel('Foo', 'Bar'),
        migrations.RenameField('AnotherModel', 'foo', 'bar'),
        migrations.RenameField('YetAnotherModel', 'foo', 'bar')
    ]

如果不更新导入名称,例如admin.py甚至更旧的迁移文件(!),则可能会遇到一些错误。

更新:正如ceasaro所提到的,较新版本的Django通常能够检测并询问是否重命名了模型。因此,请先尝试manage.py makemigrations,然后检查迁移文件。

So when I tried this, it seems you can condense Step 3 – 7:

class Migration(migrations.Migration):

    dependencies = [
        ('myapp', '0001_initial'), 
    ]

    operations = [
        migrations.RenameModel('Foo', 'Bar'),
        migrations.RenameField('AnotherModel', 'foo', 'bar'),
        migrations.RenameField('YetAnotherModel', 'foo', 'bar')
    ]

You may get some errors if you don’t update the names where it’s imported e.g. admin.py and even older migration files (!).

Update: As ceasaro mentions, newer versions of Django are usually able to detect and ask if a model is renamed. So try manage.py makemigrations first and then check the migration file.


回答 1

最初,我认为Fiver的方法很适合我,因为迁移在第4步之前都可以正常进行。但是,在任何迁移中,从“ ForeignKeyField(Foo)”到“ ForeignKeyField(Bar)”的隐式更改均不相关。这就是为什么当我想重命名关系字段时迁移失败(步骤5-8)。这可能是由于我的案例中我的“ AnotherModel”和“ YetAnotherModel”是在其他应用中分派的。

因此,我设法按照以下步骤重命名我的模型和关系字段:

我改编自方法和otranzer的特别的特技。

因此,就像Fiver一样,我们在myapp中拥有

class Foo(models.Model):
    name = models.CharField(unique=True, max_length=32)
    description = models.TextField(null=True, blank=True)

myotherapp中

class AnotherModel(models.Model):
    foo = models.ForeignKey(Foo)
    is_awesome = models.BooleanField()


class YetAnotherModel(models.Model):
    foo = models.ForeignKey(Foo)
    is_ridonkulous = models.BooleanField()

第1步:

将每个OneToOneField(Foo)或ForeignKeyField(Foo)转换为IntegerField()。(这会将相关Foo对象的ID保留为integerfield的值)。

class AnotherModel(models.Model):
    foo = models.IntegerField()
    is_awesome = models.BooleanField()

class YetAnotherModel(models.Model):
    foo = models.IntegerField()
    is_ridonkulous = models.BooleanField()

然后

python manage.py makemigrations

python manage.py migrate

第2步:(类似于Fiver的第2-4步)

更改型号名称

class Bar(models.Model):  # <-- changed model name
    name = models.CharField(unique=True, max_length=32)
    description = models.TextField(null=True, blank=True)

创建一个空迁移:

python manage.py makemigrations --empty myapp

然后像这样编辑它:

class Migration(migrations.Migration):

    dependencies = [
        ('myapp', '0001_initial'),
    ]

    operations = [
        migrations.RenameModel('Foo', 'Bar')
    ]

最终

python manage.py migrate

第三步:

将您的IntegerField()转换回其先前的ForeignKeyField或OneToOneField,但使用新的Bar模型。(以前的整型字段存储的是id,因此django理解了这一点并重新建立了连接,这很酷。)

class AnotherModel(models.Model):
    foo = models.ForeignKey(Bar)
    is_awesome = models.BooleanField()

class YetAnotherModel(models.Model):
    foo = models.ForeignKey(Bar)
    is_ridonkulous = models.BooleanField()

然后做:

python manage.py makemigrations 

非常重要的是,在这一步中,您必须修改每个新的迁移,并在RenameModel Foo-> Bar迁移上添加依赖项。因此,如果AnotherModel和YetAnotherModel都在myotherapp中,则在myotherapp中创建的迁移必须如下所示:

class Migration(migrations.Migration):

    dependencies = [
        ('myapp', '00XX_the_migration_of_myapp_with_renamemodel_foo_bar'),
        ('myotherapp', '00xx_the_migration_of_myotherapp_with_integerfield'),
    ]

    operations = [
        migrations.AlterField(
            model_name='anothermodel',
            name='foo',
            field=models.ForeignKey(to='myapp.Bar'),
        ),
        migrations.AlterField(
            model_name='yetanothermodel',
            name='foo',
            field=models.ForeignKey(to='myapp.Bar')
        ),
    ]

然后

python manage.py migrate

第4步:

最终,您可以重命名字段

class AnotherModel(models.Model):
    bar = models.ForeignKey(Bar) <------- Renamed fields
    is_awesome = models.BooleanField()


class YetAnotherModel(models.Model):
    bar = models.ForeignKey(Bar) <------- Renamed fields
    is_ridonkulous = models.BooleanField()

然后自动重命名

python manage.py makemigrations

(django应该询问您是否实际重命名了模型名称,请说是)

python manage.py migrate

就是这样!

这适用于Django1.8

At first, I thought that Fiver’s method worked for me because the migration worked well until step 4. However, the implicit changes ‘ForeignKeyField(Foo)’ into ‘ForeignKeyField(Bar)’ was not related in any migrations. This is why migration failed when I wanted to rename relationship fields (step 5-8). This might be due to the fact that my ‘AnotherModel’ and ‘YetAnotherModel’ are dispatched in other apps in my case.

So I managed to rename my models and relationship fields doing following below steps:

I adapted the method from this and particularly the trick of otranzer.

So like Fiver let’s say we have in myapp:

class Foo(models.Model):
    name = models.CharField(unique=True, max_length=32)
    description = models.TextField(null=True, blank=True)

And in myotherapp:

class AnotherModel(models.Model):
    foo = models.ForeignKey(Foo)
    is_awesome = models.BooleanField()


class YetAnotherModel(models.Model):
    foo = models.ForeignKey(Foo)
    is_ridonkulous = models.BooleanField()

Step 1:

Transform every OneToOneField(Foo) or ForeignKeyField(Foo) into IntegerField(). (This will keep the id of related Foo object as value of the integerfield).

class AnotherModel(models.Model):
    foo = models.IntegerField()
    is_awesome = models.BooleanField()

class YetAnotherModel(models.Model):
    foo = models.IntegerField()
    is_ridonkulous = models.BooleanField()

Then

python manage.py makemigrations

python manage.py migrate

Step 2: (Like step 2-4 from Fiver)

Change the model name

class Bar(models.Model):  # <-- changed model name
    name = models.CharField(unique=True, max_length=32)
    description = models.TextField(null=True, blank=True)

Create an empty migration:

python manage.py makemigrations --empty myapp

Then edit it like:

class Migration(migrations.Migration):

    dependencies = [
        ('myapp', '0001_initial'),
    ]

    operations = [
        migrations.RenameModel('Foo', 'Bar')
    ]

Eventually

python manage.py migrate

Step 3:

Transform Back your IntegerField() into their previous ForeignKeyField or OneToOneField but with the new Bar Model. (The previous integerfield was storing the id, so django understand that and reestablish the connection, which is cool.)

class AnotherModel(models.Model):
    foo = models.ForeignKey(Bar)
    is_awesome = models.BooleanField()

class YetAnotherModel(models.Model):
    foo = models.ForeignKey(Bar)
    is_ridonkulous = models.BooleanField()

Then do:

python manage.py makemigrations 

Very importantly, at this step you have to modify every new migrations and add the dependency on the RenameModel Foo-> Bar migrations. So if both AnotherModel and YetAnotherModel are in myotherapp the created migration in myotherapp must look like this:

class Migration(migrations.Migration):

    dependencies = [
        ('myapp', '00XX_the_migration_of_myapp_with_renamemodel_foo_bar'),
        ('myotherapp', '00xx_the_migration_of_myotherapp_with_integerfield'),
    ]

    operations = [
        migrations.AlterField(
            model_name='anothermodel',
            name='foo',
            field=models.ForeignKey(to='myapp.Bar'),
        ),
        migrations.AlterField(
            model_name='yetanothermodel',
            name='foo',
            field=models.ForeignKey(to='myapp.Bar')
        ),
    ]

Then

python manage.py migrate

Step 4:

Eventually you can rename your fields

class AnotherModel(models.Model):
    bar = models.ForeignKey(Bar) <------- Renamed fields
    is_awesome = models.BooleanField()


class YetAnotherModel(models.Model):
    bar = models.ForeignKey(Bar) <------- Renamed fields
    is_ridonkulous = models.BooleanField()

and then do automatic renaming

python manage.py makemigrations

(django should ask you if you actually renamed the modelname, say yes)

python manage.py migrate

And that’s it!

This works on Django1.8


回答 2

我需要做同样的事情并遵循。我一次更改了模型(Fiver回答中的步骤1和5)。然后创建模式迁移,但将其编辑为:

class Migration(SchemaMigration):
    def forwards(self, orm):
        db.rename_table('Foo','Bar')

    def backwards(self, orm):
        db.rename_table('Bar','Foo')

这工作得很好。我所有的现有数据都显示出来,其他所有表都引用了Bar fine。

从这里开始:https : //hanmir.wordpress.com/2012/08/30/rename-model-django-south-migration/

I needed to do the same thing and follow. I changed the model all at once (Steps 1 and 5 together from Fiver’s answer). Then created a schema migration but edited it to be this:

class Migration(SchemaMigration):
    def forwards(self, orm):
        db.rename_table('Foo','Bar')

    def backwards(self, orm):
        db.rename_table('Bar','Foo')

This worked perfectly. All my existing data showed up, all the other tables referenced Bar fine.

from here: https://hanmir.wordpress.com/2012/08/30/rename-model-django-south-migration/


回答 3

对于Django 1.10,我仅通过运行Makemigrations,然后为该应用程序迁移,就设法更改了两个模型类名称(包括ForeignKey和数据)。对于Makemigrations步骤,我必须确认我想更改表名称。迁移更改表的名称没有问题。

然后,我更改了ForeignKey字段的名称以使其匹配,然后Makemigrations再次要求我确认要更改名称。迁移比进行更改。

因此,我分两步进行了此操作,而无需进行任何特殊的文件编辑。起初我确实得到了错误,因为我忘记更改admin.py文件,如@wasibigeek所述。

For Django 1.10, I managed to change two model class names (including a ForeignKey, and with data) by simply running Makemigrations, and then Migrate for the app. For the Makemigrations step, I had to confirm that I wanted to change the table names. Migrate changed the names of the tables without a problem.

Then I changed the name of the ForeignKey field to match, and again was asked by Makemigrations to confirm that I wanted to change the name. Migrate than made the change.

So I took this in two steps without any special file editing. I did get errors at first because I forgot to change the admin.py file, as mentioned by @wasibigeek.


回答 4

我也遇到了v.thorey所描述的问题,发现他的方法非常有用,但可以凝结为更少的步骤,实际上是步骤5至8,如Fiver所描述的,而没有步骤1-4,只是步骤7需要更改为在步骤3之下。总体步骤如下:

步骤1:在models.py中编辑相关字段名称

class Bar(models.Model):
    name = models.CharField(unique=True, max_length=32)
    description = models.TextField(null=True, blank=True)


class AnotherModel(models.Model):
    bar = models.ForeignKey(Bar)  # <-- changed field name
    is_awesome = models.BooleanField()


class YetAnotherModel(models.Model):
    bar = models.ForeignKey(Bar)  # <-- changed field name
    is_ridonkulous = models.BooleanField()

步骤2:建立一个空的迁移

python manage.py makemigrations --empty myapp

步骤3:在步骤2中创建的迁移文件中编辑Migration类

class Migration(migrations.Migration):

dependencies = [
    ('myapp', '0001_initial'), 
]

operations = [
    migrations.AlterField(
        model_name='AnotherModel',
        name='foo',
        field=models.IntegerField(),
    ),
    migrations.AlterField(
        model_name='YetAnotherModel',
        name='foo',
        field=models.IntegerField(),
    ),
    migrations.RenameModel('Foo', 'Bar'),
    migrations.AlterField(
        model_name='AnotherModel',
        name='foo',
        field=models.ForeignKey(to='myapp.Bar'),
    ),
    migrations.AlterField(
        model_name='YetAnotherModel',
        name='foo',
        field=models.ForeignKey(to='myapp.Bar'),
    ),
    migrations.RenameField('AnotherModel', 'foo', 'bar'),
    migrations.RenameField('YetAnotherModel', 'foo', 'bar')
]

步骤4:套用迁移

python manage.py migrate

完成了

PS我已经在Django 1.9上尝试过这种方法

I also faced the problem as v.thorey described and found that his approach is very useful but can be condensed into fewer steps which are actually step 5 to 8 as Fiver described without step 1 to 4 except that step 7 needs to be changed as my below step 3. The overall steps are as follow:

Step 1: Edit the related field names in models.py

class Bar(models.Model):
    name = models.CharField(unique=True, max_length=32)
    description = models.TextField(null=True, blank=True)


class AnotherModel(models.Model):
    bar = models.ForeignKey(Bar)  # <-- changed field name
    is_awesome = models.BooleanField()


class YetAnotherModel(models.Model):
    bar = models.ForeignKey(Bar)  # <-- changed field name
    is_ridonkulous = models.BooleanField()

Step 2: Create an empty migration

python manage.py makemigrations --empty myapp

Step 3: Edit the Migration class in the migration file created in Step 2

class Migration(migrations.Migration):

dependencies = [
    ('myapp', '0001_initial'), 
]

operations = [
    migrations.AlterField(
        model_name='AnotherModel',
        name='foo',
        field=models.IntegerField(),
    ),
    migrations.AlterField(
        model_name='YetAnotherModel',
        name='foo',
        field=models.IntegerField(),
    ),
    migrations.RenameModel('Foo', 'Bar'),
    migrations.AlterField(
        model_name='AnotherModel',
        name='foo',
        field=models.ForeignKey(to='myapp.Bar'),
    ),
    migrations.AlterField(
        model_name='YetAnotherModel',
        name='foo',
        field=models.ForeignKey(to='myapp.Bar'),
    ),
    migrations.RenameField('AnotherModel', 'foo', 'bar'),
    migrations.RenameField('YetAnotherModel', 'foo', 'bar')
]

Step 4: Apply the migration

python manage.py migrate

Done

P.S. I’ve tried this approach on Django 1.9


回答 5

我正在使用Django版本1.9.4

我已按照以下步骤操作:

我刚刚将模型oldName重命名为NewName Run python manage.py makemigrations。它将要求您 Did you rename the appname.oldName model to NewName? [y/N]选择Y

运行python manage.py migrate,它将要求您

以下内容类型是陈旧的,需要删除:

appname | oldName
appname | NewName

通过外键与这些内容类型相关的任何对象也将被删除。您确定要删除这些内容类型吗?如果不确定,请回答“否”。

Type 'yes' to continue, or 'no' to cancel: Select No

它为我重命名并将所有现有数据迁移到新的命名表。

I am using Django version 1.9.4

I have follow the following steps:-

I have just rename the model oldName to NewName Run python manage.py makemigrations. It will ask you for Did you rename the appname.oldName model to NewName? [y/N] select Y

Run python manage.py migrate and it will ask you for

The following content types are stale and need to be deleted:

appname | oldName
appname | NewName

Any objects related to these content types by a foreign key will also be deleted. Are you sure you want to delete these content types? If you’re unsure, answer ‘no’.

Type 'yes' to continue, or 'no' to cancel: Select No

It rename and migrate all existing data to new named table for me.


回答 6

不幸的是,我发现了重命名迁移的问题(每个django 1.x),这些问题将旧表名保留在数据库中。

Django甚至没有在旧表上尝试任何操作,只是重命名了自己的模型。外键和索引通常存在相同的问题-Django无法正确跟踪那里的更改。

最简单的解决方案(解决方法):

class Foo(models.Model):
     name = models.CharField(unique=True, max_length=32)
     ...
Bar = Foo  # and use Bar only

真正的解决方案(一种在2次提交中切换所有索引,约束,触发器,名称等的简便方法,而对于较小的表则如此):

提交A:

  1. 创建旧模型相同的模型
# deprecated - TODO: TO BE REMOVED
class Foo(model.Model):
    ...

class Bar(model.Model):
    ...
  1. 切换代码以Bar仅与新模型一起使用。(包括架构上的所有关系)

在迁移准备中RunPython,它将数据从Foo复制到Bar(包括idFoo)

  1. 可选的优化(如果需要更大的表)

提交B :(不要着急,整个团队迁移后都要做)

  1. 旧型号的安全降落 Foo

进一步清理:

  • 壁球迁徙

Django中的错误:

Unfortunately, I found problems (each django 1.x) with rename migration which leave old table names in the database.

Django doesn’t even try anything on the old table, just rename his own model. The same problem with foreign keys, and indices in general – changes there are not tracked properly by Django.

The simplest solution (workaround):

class Foo(models.Model):
     name = models.CharField(unique=True, max_length=32)
     ...
Bar = Foo  # and use Bar only

The real solution (an easy way to switch all indices, constraints, triggers, names, etc in 2 commits, but rather for smaller tables):

commit A:

  1. create the same model as the old one
# deprecated - TODO: TO BE REMOVED
class Foo(model.Model):
    ...

class Bar(model.Model):
    ...
  1. switch code to work with new model Bar only. (including all relations on the schema)

In migration prepare RunPython, which copy data from Foo to Bar (including id of Foo)

  1. optional optimization (if needed for greater tables)

commit B: (no rush, do it when an entire team is migrated)

  1. safe drop of the old model Foo

further cleanup:

  • squash on migrations

bug in Django:


回答 7

只是想确认并添加ceasaro评论。Django 2.0现在似乎可以自动执行此操作。

我在Django 2.2.1上,我所要做的只是重命名模型并运行makemigrations

在这里,它询问我是否已将特定的类从重命名AB,我选择是,然后进行了迁移,并且一切似乎都可以正常工作。

注意我没有在project / migrations文件夹内的任何文件中重命名旧模型名称。

Just wanted to confirm and add upon ceasaro comment. Django 2.0 seems to do this automatically now.

I’m on Django 2.2.1, all I had to do what to rename the model and run makemigrations.

Here it asks if I had renamed the specific class from A to B, i chose yes and ran migrate and all seems to work.

Note I did not rename the old model name in any files inside the project/migrations folder.


回答 8

我需要重命名几个表。但是Django仅注意到一种模型重命名。发生这种情况是因为Django反复遍历添加的模型,然后删除了模型。对于每一对,它会检查它们是否属于同一应用,并且具有相同的字段。只有一个表没有要重命名的表的外键(您记得,外键包含模型类名称)。换句话说,只有一个表没有字段更改。这就是为什么它被注意到。

因此,解决方案是一次重命名一个表,在中更改模型类名称models.py,可能是views.py,然后进行迁移。之后,检查您的代码是否有其他引用(模型类名称,相关(查询)名称,变量名称)。如果需要,请进行迁移。然后,有选择地将所有这些迁移合并为一个(确保也复制导入)。

I needed to rename a couple of tables. But only one model rename was noticed by Django. That happened because Django iterates over added, then removed models. For each pair it checks if they’re of the same app and have identical fields. Only one table had no foreign keys to tables to be renamed (foreign keys contain model class name, as you remember). In other words, only one table had no field changes. That’s why it was noticed.

So, the solution is to rename one table at a time, changing model class name in models.py, possibly views.py, and making a migration. After that inspect your code for other references (model class names, related (query) names, variable names). Make a migration, if needed. Then, optionally combine all these migrations into one (make sure to copy imports as well).


回答 9

我会用@ceasaro的话,对他对这个答案的评论。

较新版本的Django可以检测到更改并询问已完成的操作。我还要补充一点,Django可能会混合一些迁移命令的执行顺序。

这将是明智的,适用小的变化和运行makemigrations以及migrate如果发生错误的迁移文件进行编辑。

某些行的执行顺序可以更改,以免出错。

I would make @ceasaro words, mine on his comment on this answer.

Newer versions of Django can detect changes and ask about what was done. I also would add that Django might mix the order of execution of some migration commands.

It would be wise to apply small changes and run makemigrations and migrate and if the error occurs the migration file can be edited.

Some lines order of execution can be changed to avoid erros.


回答 10

如果您使用的是像PyCharm这样的优秀IDE,则可以右键单击模型名称并进行重构->重命名。这免除了您遍历引用该模型的所有代码的麻烦。然后运行makemigrations并进行迁移。Django 2+只会确认名称更改。

If you are using a good IDE like PyCharm you can right click on the model name and do a refactor -> rename. This saves you the trouble of going through all your code that references the model. Then run makemigrations and migrate. Django 2+ will simply confirm name change.


回答 11

我将Django从版本10升级到版本11:

sudo pip install -U Django

-U用于“升级”),它解决了问题。

I upgraded Django from version 10 to version 11:

sudo pip install -U Django

(-U for “upgrade”) and it solved the problem.


Django 1.7-makemigrations无法检测到更改

问题:Django 1.7-makemigrations无法检测到更改

如标题所述,我似乎无法使迁移正常进行。

该应用程序最初的版本低于1.6,因此我知道迁移最初不会进行,并且如果我运行,python manage.py migrate我会得到:

Operations to perform:
  Synchronize unmigrated apps: myapp
  Apply all migrations: admin, contenttypes, auth, sessions
Synchronizing apps without migrations:
  Creating tables...
  Installing custom SQL...
  Installing indexes...
Running migrations:
  No migrations to apply.

如果我对中的任何模型进行了更改myapp,它仍会像预期的那样未迁移。

但是如果我跑步,python manage.py makemigrations myapp我会得到:

No changes detected in app 'myapp'

似乎与我运行命令的方式或方式无关紧要,它永远不会将应用程序检测为更改,也不会向该应用程序添加任何迁移文件。

是否有任何方法可以迫使应用程序迁移并实质上说“这是我的工作基础”或其他内容?还是我错过了什么?

如果有帮助的话,我的数据库就是PostgreSQL。

As the title says, I can’t seem to get migrations working.

The app was originally under 1.6, so I understand that migrations won’t be there initially, and indeed if I run python manage.py migrate I get:

Operations to perform:
  Synchronize unmigrated apps: myapp
  Apply all migrations: admin, contenttypes, auth, sessions
Synchronizing apps without migrations:
  Creating tables...
  Installing custom SQL...
  Installing indexes...
Running migrations:
  No migrations to apply.

If I make a change to any models in myapp, it still says unmigrated, as expected.

But if I run python manage.py makemigrations myapp I get:

No changes detected in app 'myapp'

Doesn’t seem to matter what or how I run the command, it’s never detecting the app as having changes, nor is it adding any migration files to the app.

Is there any way to force an app onto migrations and essentially say “This is my base to work with” or anything? Or am I missing something?

My database is a PostgreSQL one if that helps at all.


回答 0

如果要从django 1.6中制作的现有应用程序进行转换,则需要执行文档中列出的一个第一步(如我所知):

python manage.py makemigrations your_app_label

该文档没有明显表明您需要在命令中添加应用标签,因为它首先告诉您要做的是python manage.py makemigrations失败。最初的迁移是在1.7版中创建的应用程序完成的,但是如果您来自1.6版,则不会进行。有关更多详细信息,请参见文档中的“向应用程序添加迁移”

If you’re changing over from an existing app you made in django 1.6, then you need to do one pre-step (as I found out) listed in the documentation:

python manage.py makemigrations your_app_label

The documentation does not make it obvious that you need to add the app label to the command, as the first thing it tells you to do is python manage.py makemigrations which will fail. The initial migration is done when you create your app in version 1.7, but if you came from 1.6 it wouldn’t have been carried out. See the ‘Adding migration to apps’ in the documentation for more details.


回答 1

可能由于以下原因而发生:

  1. 您没有在以下位置的INSTALLED_APPS列表中添加应用程序settings.py (您必须在应用程序文件夹的apps.py中添加应用程序名称或虚线路径到AppConfig的子类,具体取决于所使用的Django版本)。请参阅文档:INSTALLED_APPS
  2. migrations这些应用程序内没有文件夹。(解决方案:只需创建该文件夹)。
  3. 您没有这些应用程序__init__.py文件migrations夹中的文件。(解决方案:只需创建一个名称为__init__.py的空文件)
  4. __init__.py的应用文件夹中没有文件。(解决方案:只需创建一个名称为__init__.py的空文件)
  5. models.py的应用程序中没有文件
  6. 您的Python类(假定是模型)models.py不会继承django.db.models.Model
  7. 您在定义模型时存在语义错误 models.py

注意: 一个常见的错误是migrations.gitignore文件中添加文件夹。从远程存储库克隆后,本地存储库中的文件migrations夹和/或__init__.py文件将丢失。这导致问题。

我建议通过在文件中添加以下几行来忽略迁移.gitignore文件

*/migrations/*
!*/migrations/__init__.py

This may happen due to the following reasons:

  1. You did not add the app in INSTALLED_APPS list in settings.py (You have to add either the app name or the dotted path to the subclass of AppConfig in apps.py in the app folder, depending on the version of django you are using). Refer documentation: INSTALLED_APPS
  2. You don’t have migrations folder inside those apps. (Solution: just create that folder).
  3. You don’t have __init__.py file inside migrations folder of those apps. (Solution: Just create an empty file with name __init__.py)
  4. You don’t have an __init__.py file inside the app folder. (Solution: Just create an empty file with name __init__.py)
  5. You don’t have a models.py file in the app
  6. Your Python class (supposed to be a model) in models.py doesn’t inherit django.db.models.Model
  7. You have some semantic mistake in definition of models in models.py

Note: A common mistake is to add migrations folder in .gitignore file. When cloned from remote repo, migrations folder and/or __init__.py files will be missing in local repo. This causes problem.

I suggest to gitignore migration files by adding the following lines to .gitignore file

*/migrations/*
!*/migrations/__init__.py

回答 2

好的,看来我错过了一个明显的步骤,但是在其他人也这样做的情况下发布了此步骤。

当升级到1.7时,我的模型变成了不受管理的(managed = False)-我像True以前一样拥有它们,但似乎已还原。

删除该行(默认情况下为True)然后makemigrations立即运行就构成了一个迁移模块,现在它可以正常工作了。makemigrations将不适用于非托管表(事后看来很明显)

Ok, looks like I missed an obvious step, but posting this in case anyone else does the same.

When upgrading to 1.7, my models became unmanaged (managed = False) – I had them as True before but seems it got reverted.

Removing that line (To default to True) and then running makemigrations immediately made a migration module and now it’s working. makemigrations will not work on unmanaged tables (Which is obvious in hindsight)


回答 3

我的解决方案未在此处介绍,因此我将其发布。我一直在使用syncdb一个项目-只是为了使其启动并运行。然后,当我尝试开始使用Django迁移时,它首先伪造了它们,然后说是“ OK”,但数据库没有任何反应。

我的解决方案是只删除应用程序的所有迁移文件,以及django_migrations表中应用程序迁移的数据库记录。

然后,我进行了以下初步迁移:

./manage.py makemigrations my_app

其次是:

./manage.py migrate my_app

现在,我可以毫无问题地进行迁移了。

My solution was not covered here so I’m posting it. I had been using syncdb for a project–just to get it up and running. Then when I tried to start using Django migrations, it faked them at first then would say it was ‘OK’ but nothing was happening to the database.

My solution was to just delete all the migration files for my app, as well as the database records for the app migrations in the django_migrations table.

Then I just did an initial migration with:

./manage.py makemigrations my_app

followed by:

./manage.py migrate my_app

Now I can make migrations without a problem.


回答 4

同意@furins。如果一切似乎都井然有序,但是仍然出现此问题,请检查是否有任何名称与要在Model类中添加的属性相同的属性方法。

  1. 删除名称与要添加的属性类似的方法。
  2. manage.py makemigrations my_app
  3. manage.py迁移my_app
  4. 重新添加方法。

Agree with @furins. If everything seems to be in order and yet this problem arises, checkout if there is any property method with same title as the attribute which you are trying to add in the Model class.

  1. Remove method with similar name as attribute you are adding.
  2. manage.py makemigrations my_app
  3. manage.py migrate my_app
  4. Add the methods back.

回答 5

这是一个愚蠢的错误,但是在模型类的字段声明行的末尾有一个逗号,使该行无效。

复制粘贴def时会发生这种情况。从迁移本身定义为数组。

虽然这可能会帮助某人:-)

This is kind of a stupid mistake to make, but having an extra comma at the end of the field declaration line in the model class, makes the line have no effect.

It happens when you copy paste the def. from the migration, which itself is defined as an array.

Though maybe this would help someone :-)


回答 6

也许我来不及了,但是您是否尝试migrations在应用中创建一个__init__.py文件夹,其中包含文件?

Maybe I am too late but did you try to have a migrations folder in your app with a __init__.py file in it?


回答 7

也许这会帮助某人。我正在使用嵌套应用程序。project.appname,我实际上在INSTALLED_APPS中有project和project.appname。从INSTALLED_APPS中删除项目可以检测到更改。

Maybe this will help someone. I was using a nested app. project.appname and I actually had project and project.appname in INSTALLED_APPS. Removing project from INSTALLED_APPS allowed the changes to be detected.


回答 8

答案是在此stackoverflow帖子上,由cdvv7788 在Django 1.7中进行迁移

如果是第一次迁移该应用程序,则必须使用:

manage.py makemigrations myappname完成后,您可以执行以下操作:

manage.py migration如果您的应用程序已包含在数据库中,请修改其模型并且不更新makemigrations上的更改,则您可能尚未迁移它。将您的模型改回其原始形式,运行第一个命令(使用应用程序名称)并迁移…它将对其进行伪造。完成后,将更改放回模型中,请运行makemigrations并再次进行迁移,它应该可以正常工作。

我遇到了完全相同的麻烦,并且执行上述操作完全正常。

我已将django应用程序移至cloud9,由于某种原因,我从未进行过初始迁移。

The answer is on this stackoverflow post, by cdvv7788 Migrations in Django 1.7

If it is the first time you are migrating that app you have to use:

manage.py makemigrations myappname Once you do that you can do:

manage.py migrate If you had your app in database, modified its model and its not updating the changes on makemigrations you probably havent migrated it yet. Change your model back to its original form, run the first command (with the app name) and migrate…it will fake it. Once you do that put back the changes on your model, run makemigrations and migrate again and it should work.

I was having the exact same trouble and doing the above worked perfectly.

I had moved my django app to cloud9 and for some reason I never caught the initial migration.


回答 9

以下为我工作:

  1. 将应用名称添加到settings.py
  2. 使用’python manage.py makemigrations’
  3. 使用’python manage.py migration’

为我工作:Python 3.4,Django 1.10

Following worked for me:

  1. Add the app name to settings.py
  2. use ‘python manage.py makemigrations’
  3. use ‘python manage.py migrate’

Worked for me: Python 3.4, Django 1.10


回答 10

像我这样不喜欢迁移的人可以使用以下步骤。

  1. 删除您要同步的更改。
  2. 运行python manage.py makemigrations app_label初始迁移。
  3. python manage.py migrate进行更改之前,运行以创建表。
  4. 粘贴您在第一步中删除的更改。
  5. 运行步骤2.和3.。

如果您对这些步骤感到困惑,请阅读迁移文件。更改它们以更正您的架构或删除不需要的文件,但不要忘记更改下一个迁移文件的依赖项;)

我希望这会在将来对某人有所帮助。

People like me who don’t like migrations can use steps below.

  1. Remove changes what you want to sync.
  2. Run python manage.py makemigrations app_label for the initial migration.
  3. Run python manage.py migrate for creating tables before you make changes.
  4. Paste changes which you remove at first step.
  5. Run 2. and 3. steps.

If you confused any of these steps, read the migration files. Change them to correct your schema or remove unwanted files but don’t forget to change next migration file’s dependencies part ;)

I hope this will help someone in future.


回答 11

你要检查settings.pyINSTALLED_APPS列表,并确保所有与模型的应用程序在那里上市。

makemigrations在项目文件夹中运行意味着它将寻找更新与settings.py项目中包含的所有应用程序相关的所有表。包含它后,makemigrations将自动包含该应用程序(这样可以节省大量工作,因此您不必makemigrations app_name为项目/站点中的每个应用程序都运行)。

You want to check the settings.py in the INSTALLED_APPS list and make sure all the apps with models are listed in there.

Running makemigrations in the project folder means it will look to update all the tables related to all the apps included in settings.py for the project. Once you include it, makemigrations will automatically include the app (this saves a lot of work so you don’t have to run makemigrations app_name for every app in your project/site).


回答 12

以防万一您有一个不能由makemigrations标识的特定字段:检查两次是否具有相同名称的属性。

例:

field = django.db.models.CharField(max_length=10, default = '', blank=True, null=True)

# ... later

@property
def field(self):
    pass

该属性将“覆盖”字段定义,因此更改不会被 makemigrations

Just in case you have a specific field that does not get identified by makemigrations: check twice if you have a property with the same name.

example:

field = django.db.models.CharField(max_length=10, default = '', blank=True, null=True)

# ... later

@property
def field(self):
    pass

the property will “overwrite” the field definition so changes will not get identified by makemigrations


回答 13

确保您的模型不是abstract。我实际上犯了那个错误,花了一段时间,所以我以为会发布它。

Make sure your model is not abstract. I actually made that mistake and it took a while, so I thought I’d post it.


回答 14

添加此答案是因为只有此方法对我有帮助。

我删除了migrations文件夹run makemigrationsmigrate
它仍然说:没有迁移申请。

我转到migrate文件夹并打开了最后一个创建的文件,
注释了我想要的迁移(已检测到并在此输入)
migrate再次运行。

这基本上是手动编辑迁移文件。
仅当您了解文件内容时,才执行此操作。

Adding this answer because only this method helped me.

I deleted the migrations folder run makemigrations and migrate.
It still said: No migrations to apply.

I went to migrate folder and opened the last created file,
comment the migration I wanted(It was detected and entered there)
and run migrate again.

This basically editing the migrations file manually.
Do this only if you understand the file content.


回答 15

schemamigration my_app --initial重命名旧的迁移文件夹后是否使用过?试试吧。可能会工作。如果不是,请尝试重新创建数据库并进行syncdb + migrate。它对我有用…

Did u use schemamigration my_app --initial after renaming old migration folder? Try it. Might work. If not – try to recreate the database and make syncdb+migrate. It worked for me…


回答 16

遇到相同的问题确保您在models.py中定义了任何类,您必须必须继承models.Model类。

class Product(models.Model):
    title = models.TextField()
    description = models.TextField()
    price = models.TextField()

Had the same problem Make sure whatever classes you have defined in models.py, you must have to inherit models.Model class.

class Product(models.Model):
    title = models.TextField()
    description = models.TextField()
    price = models.TextField()

回答 17

我不得不两次运行makemigrations和各种奇怪的行为时遇到了同样的问题。事实证明,问题的根源在于我正在使用一个函数来设置模型中的默认日期,因此每次我进行makemigrations时,迁移都会检测到更改。这个问题的答案使我走上了正确的轨道:避免进行重新创建日期字段的迁移

I had the same problem with having to run makemigrations twice and all sorts of strange behaviour. It turned out the root of the problem was that I was using a function to set default dates in my models so migrations was detecting a change every time I ran makemigrations. The answer to this question put me on the right track: Avoid makemigrations to re-create date field


回答 18

我最近将Django从1.6升级到1.8,并且几乎没有应用和迁移。我使用了south并schemamigrations在Django 1.6中创建了迁移,而在Django 1.8中删除了该迁移。

当我在升级后添加新型号时,该makemigrations命令未检测到任何更改。然后,我尝试了@drojf建议的解决方案(第一个答案),它工作正常,但未能应用假的初始迁移(python manage.py --fake-initial)。我这样做是因为我的表(旧表)已经创建。

最终,这对我有用,从models.py中删除了新模型(或模型更改),然后必须删除(或重命名以进行安全备份)所有应用程序的迁移文件夹,并manage.py为所有应用程序运行python makemigrations,然后执行了python manage.py migrate --fake-initial。这就像一个魅力。为所有应用创建初始迁移并进行伪初始迁移后,便添加了新模型,并遵循makemigrations该应用的常规流程进行迁移。现在已检测到更改,一切正常。

我只是想在这里分享它,如果有人遇到相同的问题(schemamigrations他们的应用程序有问题),可能会对他们有所帮助:)

I recently upgraded Django from 1.6 to 1.8 and had few apps and migrations for them. I used south and schemamigrations for creating migrations in Django 1.6, which is dropped in Django 1.8.

When I added new models after upgrade, the makemigrations command wasn’t detecting any changes. And then I tried the solution suggested by @drojf (1st answer), it worked fine, but failed to apply fake initial migration (python manage.py --fake-initial). I was doing this as my tables (old tables) were already created.

Finally this worked for me, removed new models (or model changes) from models.py and then had to delete (or rename for safety backup) migrations folder of all apps and run python manage.py makemigrations for all apps, then did python manage.py migrate --fake-initial. This worked like a charm. Once initial migration is created for all apps and fake initial migrated, then added new models and followed regular process of makemigrations and migrate on that app. The changes were detected now and everything went fine.

I just thought of sharing it here, if someone faces same problem (having schemamigrations of south for their apps), it might help them :)


回答 19

也许可以帮助某人,但我遇到了同样的问题。

我已经用序列化程序类和视图创建了两个表。因此,当我想更新时,出现了此错误。

我按照以下步骤操作:

  1. 我做了 .\manage.py makemigrations app
  2. 我执行了 .\manage.py migrate
  3. 我删除了我的两个表 models.py
  4. 我从序列化程序和视图类中删除了对表的所有引用。
  5. 我执行了step 12
  6. 我只是在 models.py
  7. 我再次执行步骤5
  8. 我恢复了所有更改。

如果您正在使用Pycharm,则本地历史记录将非常有帮助。

Maybe that can help someone, I had the same problem.

I’ve already created two tables with the serializer class and the views. So when I wanted to updated, I had this error.

I followed this steps:

  1. I made .\manage.py makemigrations app
  2. I executed .\manage.py migrate
  3. I erased both tables of my models.py
  4. I erased all reference to my tables from serializer and view class.
  5. I executed step 1 and 2.
  6. I retrieved my changes just in the models.py
  7. I executed again step 5.
  8. I restored all my changes.

If you’re working with Pycharm, local history is very helpfull.


回答 20

也许这会帮助某人。

我已经删除了,models.py并希望makemigrations创建DeleteModel语句。

记住要删除*.pyc文件!

Maybe this will help someone.

I’ve deleted my models.py and expected makemigrations to create DeleteModel statements.

Remember to delete *.pyc files!


回答 21

./manage makemigrations
./manage migrate

迁移会跟踪对数据库的更改,因此,如果您从非托管更改为托管,则需要确保您的数据库表与您要处理的模型有关的最新信息。

如果您仍处于开发模式,我个人决定删除我的IDE以及与我的模型相关的django_migrations表中的迁移文件,然后重新运行上述命令。

记住:如果您的迁移在IDE中以_001结尾,在数据库中以_003结尾。Django仅会查看您是否有以_004结尾的迁移来更新任何内容。

2(代码和数据库迁移)是链接在一起的,并且可以协同工作。

快乐的编码。

./manage makemigrations
./manage migrate

Migrations track changes to DB so if youre changing from unmanaged to managed, you’ll need to make sure that youre database table is up to date relating to the Model you’re dealing with.

If you are still in dev mode, I personally decided to delete the migration files in my IDE as well as in the django_migrations table relating to my Model and rerun the above command.

REMEMBER: if you have a migration that ends with _001 in your IDE & _003 in your database. Django will only see if you have a migration ending with _004 for anything to update.

The 2 (code & db migrations) are linked and work in tandem.

Happy coding.


回答 22

  1. 删除您要同步的更改。
  2. 运行python manage.py makemigrations app_label进行初始迁移。
  3. 进行更改之前,请运行python manage.py migration来创建表。
  4. 粘贴您在第一步中删除的更改。
  5. 运行步骤2和3。
  1. Remove changes what you want to sync.
  2. Run python manage.py makemigrations app_label for the initial migration.
  3. Run python manage.py migrate for creating tables before you make changes.
  4. Paste changes which you remove at first step.
  5. Run 2. and 3. steps

回答 23

添加了此答案,因为上面没有其他可用的方法适合我。

在我的情况下,发生了更奇怪的事情(Django 1.7版本),在我的models.py文件的末尾有一个“额外”行(这是一个空行),当我执行python manage.py makemigrations命令时,结果是:“未检测到更改”。

要解决此问题,我删除了我的models.py文件末尾的“空白行”,并再次运行了该命令,所有问题均已修复,并且检测到对models.py所做的所有更改!

Added this answer because none of other available above worked for me.

In my case something even more weird was happening (Django 1.7 Version), In my models.py I had an “extra” line at the end of my file (it was a blank line) and when I executed the python manage.py makemigrations command the result was: “no changes detected”.

To fix this I deleted this “blank line” that was at the end of my models.py file and I did run the command again, everything was fixed and all the changes made to models.py were detected!


回答 24

您可能需要使用以下命令来伪造初始迁移

python manage.py migrate --fake-initial

You may need to fake the initial migrations using the command below

python manage.py migrate --fake-initial

回答 25

首先,此解决方案适用于在heroku服务器上部署期间遇到相同问题的用户,而我也面临相同的问题。

要进行部署,有一个强制性步骤是在settings.py文件中添加django_heroku.settings(locals())。

更改:当我将上述行更改为django_heroku.settings(locals(),database = False)时,它可以正常工作。

First this solution is applicable to those who are facing the same issue during deployment on heroku server, I was facing same issue.

To deploy, there is a mandatory step which is to add django_heroku.settings(locals()) in settings.py file.

Changes: When I changed the above line to django_heroku.settings(locals(), databases=False), it worked flawlessly.


回答 26

就我而言,我需要将模型添加到定义了模型的models文件夹的_ init _.py文件中:

from myapp.models.mymodel import MyModel

In my case I needed to add my model to the _init_.py file of the models folder where my model was defined:

from myapp.models.mymodel import MyModel

回答 27

添加我的2c,因为这些解决方案都不适合我,但这确实…

我刚刚运行manage.py squashmigrations并删除了旧的迁移(django.migrations数据库表中的文件和行)。

在最后一个迁移文件中,这样留下了一行:

replaces = [(b'my_app', '0006_auto_20170713_1735'), (b'my_app', '0007_auto_20170713_2003'), (b'my_app', '0008_auto_20170713_2004')]

这显然使Django感到困惑,并导致了奇怪的行为:运行manage.py makemigrations my_app将重新创建初始迁移,就好像它们不存在一样。删除replaces...线路可解决问题!

Adding my 2c, since none of these solutions worked for me, but this did…

I had just run manage.py squashmigrations and removed the old migrations (both the files and lines in the the django.migrations database table).

This left a line like this in the last migration file:

replaces = [(b'my_app', '0006_auto_20170713_1735'), (b'my_app', '0007_auto_20170713_2003'), (b'my_app', '0008_auto_20170713_2004')]

This apparently confused Django and caused weird behavior: running manage.py makemigrations my_app would recreate the initial migration as if none existed. Removing the replaces... line fixed the problem!


回答 28

python manage.py makemigrations帐户“帐户”的迁移:accounts \ migrations \ 0001_initial.py-创建模型客户-创建模型标签-创建模型产品-创建模型订单

注意:这里的“帐户”是我的应用名称

python manage.py makemigrations accounts Migrations for ‘accounts’: accounts\migrations\0001_initial.py – Create model Customer – Create model Tag – Create model Product – Create model Order

Note: here “accounts” is my app name