将自定义迁移限制为一个模型

Limit custom migration to one model

我已决定为我的网站实施注册选项,我按照其中一个答案中的建议使用了 this tutorial (signup with confirmation part). Following this material I have created Profile module to hold some info. Everything (seems to be) working now, but the problem is that old profiles throws relatedObjectDoesNotExist error. According to these two questions (, ) I need to make a migration to create profiles for old user accounts. I tried to follow this doc,但后来我尝试 运行 迁移时出现以下错误:KeyError: ('stv', 'bazinekaina')

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

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

我的相关models.py代码:

    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 对我来说还是很新的。

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

删除该迁移并 运行:

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

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