【问题标题】:Limit custom migration to one model将自定义迁移限制为一个模型
【发布时间】:2019-11-12 08:02:04
【问题描述】:

我决定为我的网站实施注册选项,我使用了this tutorial(带有确认部分的注册)。按照这个材料,我创建了 Profile 模块来保存一些信息。现在一切(似乎)都在工作,但问题是旧的配置文件会抛出 relatedObjectDoesNotExist 错误。根据这两个问题(firstsecond),我需要进行迁移以为旧用户帐户创建配置文件。我尝试按照其中一个答案中的建议遵循此doc,但随后我尝试运行迁移,但出现以下错误:KeyError: ('stv', 'bazinekaina')

stv 是我的应用程序的名称,bazinekaina 是我需要创建配置文件之后的下一个模型的名称。

如何限制仅迁移到第一个模型?

我的相关@​​987654329@代码:

    class Profile(models.Model):
        user = models.OneToOneField(User, on_delete=models.CASCADE)
        email_confirmed = models.BooleanField(default=False)
        first_name = models.CharField(max_length=30)
        last_name = models.CharField(max_length=30)
        email = models.EmailField(max_length=254)

    @receiver(post_save, sender=User)
    def update_user_profile(sender, instance, created, **kwargs):
        if created:
            Profile.objects.get(user=instance)
        instance.profile.save()

#next model, this one throws an error, despite the fact it should not be touched at all
class BazineKaina(models.Model):
    #bazines kainos modelis

    bazka = models.DecimalField(max_digits=5, decimal_places=2)

    data = models.DateField(auto_now=False, auto_now_add=True)

    def __str__(self):
        return str(self.bazka)

    class Meta:
        verbose_name_plural = "Bazinė kaina"
        get_latest_by = 'data'

使用python manage.py makemigrations --empty stv 命令创建的迁移文件,命名为0001_initial.py

from django.db import migrations, models

def sukurti_profilius(apps, schema_editor):
    Profile = apps.get_model("stv", "Profile")
    for user in Profile.objects.all():
        Profile.objects.get_or_create(user=user)

class Migration(migrations.Migration):

    dependencies = [
    ]

    operations = [
    ]

我应该如何以及如何解决以阻止迁移应用于不相关的模型(并引发错误)?

对不起,如果这是基本问题,但整个 django 对我来说仍然很新。

【问题讨论】:

  • 如果您的旧配置文件出现错误,请删除所有以前的用户并删除所有迁移文件并重新执行 makemigrations 和迁移命令
  • 就是这样,我想通过为他们创建配置文件来避免删除旧用户。
  • 在模型后保存方法中尝试使用 get_or_create 方法

标签: python django django-models django-migrations


【解决方案1】:

如果您的迁移名为 0001_initial,则意味着您没有实际为配置文件模型创建表的迁移。

删除该迁移并运行:

python manage.py makemigrations stv
python manage.py makemigrations stv --empty --name create_profiles

然后你应该有一个文件 0002_create_profiles.py 并将创建配置文件的逻辑放在那里。

【讨论】:

  • 原来我弄乱了我的迁移文件,从 Git 重新下载并尝试了你的建议。结合对我代码其他部分的一些其他调整,我现在一切正常,希望我也能设法将其移出开发。
猜你喜欢
  • 1970-01-01
  • 2021-06-03
  • 2015-03-30
  • 2020-02-16
  • 2015-02-03
  • 2013-03-18
  • 1970-01-01
  • 2017-08-05
相关资源
最近更新 更多