【发布时间】:2022-07-22 08:33:40
【问题描述】:
我尝试在 Django 中向我的 ManyToMany 关系模型中添加一个字段。 因此,我一步一步地创建了新模型并应用了 makemigrations 和 migrate。 我检查了我的 postgresql 数据库中有新表。
现在,在我在 ManyToMany 字段中添加 through 关键字之前,我想在迁移文件中编写一个函数,将以前的 ManyToMany 表的旧数据复制到带有附加字段的新表中。
我遵循了此处解释的解决方案: Django migration error :you cannot alter to or from M2M fields, or add or remove through= on M2M fields
我想测试将在测试函数中迁移数据的函数,但我不明白该怎么做。
这是我的代码:
调查/模型:
class Survey(BaseModel):
name = models.CharField(max_length=256, help_text='Survey name')
user = models.ManyToManyField(User, blank=True, help_text='patient')
调查/模型:
class SurveyStatus(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
survey = models.ForeignKey(Survey, on_delete=models.CASCADE)
survey_status = models.CharField(max_length=10,
blank=True,
null=True,
choices=STATUS_SURVEY_CHOICES,
)
我写的需要将数据从之前的M2M复制到新的函数如下:
def create_through_relations(apps, schema_editor):
Survey = apps.get_model('survey', 'Survey')
SurveyStatus = apps.get_model('survey', 'SurveyStatus')
for survey in Survey.objects.all():
for user in survey.user.all():
SurveyStatus(
user=user,
survey=survey,
survey_status='active'
).save()
- 我不明白什么是应用程序?因为它不被python识别
- 我不明白为什么我需要 schema_editor,因为它没有被使用
- 它也无法识别我的 Survey 或 SurveyStatus 模型
当我尝试运行这个脚本时
if __name__ == "__main__":
create_through_relations(survey)
我遇到了这个错误
NameError: 名称“调查”未定义
如果我尝试了这个功能
from django.apps import apps
def create_through_relations():
Survey = apps.get_model('survey', 'Survey')
SurveyStatus = apps.get_model('survey', 'SurveyStatus')
for survey in Survey.objects.all():
for user in survey.user.all():
SurveyStatus(
user=user,
survey=survey,
survey_status='active'
).save()
当我尝试运行这个脚本时
if __name__ == "__main__":
create_through_relations()
我遇到了这个错误
django.core.exceptions.AppRegistryNotReady:模型尚未加载。
如果有人可以帮助并解释我如何解决。谢谢
【问题讨论】:
标签: django many-to-many django-migrations