2

I am desperately trying to get along with Django migrations, please help!

This is what I have:

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

This is what I need:

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

"number" is supposed to have the data that was in id before. While doing this Django creates the default ID field. This one needs to have the same IDs as before in order to not break relations with other tables.

Can you please help? I tried a lot of things to tackle this, but I really don't know how to do it. I need a step by step guide. The logical way would be to just clone the id field, but I don't know how and where to do that.

Thank you so much for your help! Already wasted a few days on this ._.

JasonTS
  • 2,479
  • 4
  • 32
  • 48

1 Answers1

0

After you have added the number field to your ReceiptNumber model, run makemigrations. Now alter the operations list in the migration to do something like this:

# 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)
Matt
  • 8,758
  • 4
  • 35
  • 64
  • Hi, thanks for the input, but I need the number field to be an integer only. No unique and no primary key. Instaed I need the default ID field as a pk and just want to have the current data in the number field. – JasonTS May 18 '17 at 15:45
  • do you want this number to be in database? – zaidfazil May 18 '17 at 15:49