如何将自定义id字段转换为普通整数字段?

时间:2017-05-18 15:23:24

标签: django django-models django-migrations django-database django-1.11

我拼命想与Django迁移相处,请帮忙!

这就是我所拥有的:

class ReceiptNumber(models.Model):
    id = models.AutoField(primary_key=True, unique=True)

这就是我需要的:

class ReceiptNumber(models.Model):
    number = models.IntegerField()

“number”应该包含之前为id的数据。在执行此操作时,Django会创建默认ID字段。这个需要具有与以前相同的ID,以便不破坏与其他表的关系。

你能帮帮忙吗?我尝试了很多东西来解决这个问题,但我真的不知道该怎么做。我需要一步一步的指导。逻辑方式是克隆id字段,但我不知道如何以及在何处进行。

非常感谢你的帮助!已经浪费了几天._。

1 个答案:

答案 0 :(得分:0)

number字段添加到ReceiptNumber模型后,请运行makemigrations。现在更改迁移中的operations列表,执行以下操作:

# This is your migration
from django.db import migrations, models

def copy_id_to_number(apps, schema_editor):
    ReceiptNumber = apps.get_model('receipts_app', 'ReceiptNumber')

    for receipt_number in ReceiptNumber.objects.all():
        receipt_number.save()


class Migration(migrations.Migration):

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

    operations = [
        migrations.AddField(
            model_name='receiptnumber',
            name='number',
            field=models.IntegerField(default=1),
            preserve_default=False,
        ),
        migrations.RunPython(copy_id_to_number),
    ]    

# This should be in your models

class ReceiptNumber(models.Model):
    number = models.IntegerField()

    def save(self, *args, **kwargs):
        """
        Overriden to ensure the `number` field is always the same as the `id`.
        """
        # make sure `id` is set
        if not self.pk:
            super().save(*args, **kwargs)

        if not self.number:
            self.number = self.pk

        return super().save(*args, **kwargs)