Skip to main content
 首页 » 编程设计

python之makemigrations 没有检测到新模型

2025年05月04日8Terrylee

Django 1.11。我最近将以下模块添加到 myapp.models:

from django.db import models 
from ordered_model.models import OrderedModel 
 
from .songs import Song 
 
class Service(models.Model): 
    name = models.CharField(max_len=200, unique=True) 
    date = models.DateField(blank=True) 
    items = models.ManyToManyField(ServiceItem) 
 
    class Meta: 
        ordering = ('-date', 'name') 
 
class ServiceItem(OrderedModel): 
    item = models.ForeignKey(Song) 
    song_custom_order = models.CharField(max_len=50, blank=True) 
    order_with_respect_to = 'service' 
 
    class Meta(OrderedModel.Meta): 
        pass 

我在另一个模块中有其他模型(在同一目录中)。当我运行 ./manage.py makemigrations 时,脚本会在我的其他模块中找到我的更改,但在这个模块中找不到。 FWIW,这个模块是全新的代码,之前没有迁移历史。

知道为什么这些更改没有被采纳吗?

请您参考如下方法:

模型必须导入到 models 包的 __init__.py 文件中。来自docs :

The manage.py startapp command creates an application structure that includes a models.py file. If you have many models, organizing them in separate files may be useful.

To do so, create a models package. Remove models.py and create a myapp/models/ directory with an __init__.py file and the files to store your models. You must import the models in the __init__.py file. For example, if you had organic.py and synthetic.py in the models directory:

myapp/models/__init__.py

from .organic import Person 
from .synthetic import Robot