Question:
How to migrate `DateTimeField` to `DateField` in Django?

To migrate a ‘DateTimeField’ to a ‘DateField’ in Django, you have to follow the elbow mentioned general steps:


  1. First add a field assignedtip_date that contains NULL for a start;

  2. Then run a data migration that populates the field with the truncated part of the assignedtip;

  3. Then remove the assginedtip field; and

  4. Finally rename the assginedtip_date field to assignedtip.


The migration thus will look like: 


# app_name/migrations/0123_some_name.py


from django.db import migrations, models

from django.db.models.functions import TruncDate



def migrate_date(apps, schema_editor):

    MyModel = apps.get_model("app_name", "MyModel")

    MyModel.objects.update(assignedtip_date=TruncDate('assignedtip'))



class Migration(migrations.Migration):

    dependencies = [("migrations", "0001_initial")]


    operations = [

        migrations.AddField(

            "MyModel", "assignedtip_date", models.DateField(null=True)

        ),

        migrations.RunPython(migrate_date),

        migrations.RemoveField("MyModel", "assignedtip"),

        migrations.RenameField("MyModel", "assignedtip_date", "assignedtip"),

    ]


Answered by:> Willem Van Onsem

Credit:> Stackoverflow


Suggested reads:

>How to create a One Page App with Angular.js, Node.js and MongoDB?

>How to Create an array based on two other arrays in Php

>How To Create Nested Table Structure In Angular?

>How to Create_function deprecated in PHP?

>How to delete duplicate names from Array in Typescript?

>How to do PHP Decryption from Node.js Encryption

>How to Set up the Android Emulator


Ritu Singh

Ritu Singh

Submit
0 Answers