Search code examples
djangopostgresqldjango-modelsdjango-migrations

Django. Every migration repeat "Alter field..."


My model looks like this:

class Deal(models.Model):
    in_quantity = models.IntegerField()
    exchange = models.CharField(max_length=255)
    note = models.TextField(max_length=10000, null=True)
    time_deal = models.DateTimeField(default=datetime.now())
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

And every migration I get this operation:

    - Alter field time_deal on deal

here is the example of the migration:

class Migration(migrations.Migration):

    dependencies = [
        ("portfolio", "0024_rename_quantity_deal_in_quantity_and_more"),
    ]

    operations = [
        migrations.AlterField(
            model_name="deal",
            name="note",
            field=models.TextField(max_length=10000, null=True),
        ),
        migrations.AlterField(
            model_name="deal",
            name="time_deal",
            field=models.DateTimeField(
                default=datetime.datetime(2023, 4, 26, 16, 59, 46, 769292)
            ),
        ),
        migrations.AlterField(
            model_name="historicaldeal",
            name="note",
            field=models.TextField(max_length=10000, null=True),
        ),
        migrations.AlterField(
            model_name="historicaldeal",
            name="time_deal",
            field=models.DateTimeField(
                default=datetime.datetime(2023, 4, 26, 16, 59, 46, 769292)
            ),
        ),
    ]

Could you help me to avoid it in every migration?

I searched for a solution on the internet, but found nothing.


Solution

  • You should not pass datetime.now(), since that will each time evaluate and thus create a new migrations.

    You can pass a callable instead, and then it will be evaluated when needed:

    class Deal(models.Model):
        in_quantity = models.IntegerField()
        exchange = models.CharField(max_length=255)
        note = models.TextField(max_length=10000, null=True)
        time_deal = models.DateTimeField(default=datetime.now)
        created = models.DateTimeField(auto_now_add=True)
        updated = models.DateTimeField(auto_now=True)

    if you do not want to make the field editable, Django also offers a auto_now_add=True [Django-doc].