1

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.

Ivan Starostin
  • 8,798
  • 5
  • 21
  • 39

1 Answers1

0

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].

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555