DCR
DCR

Reputation: 15700

use python instead of django shell

I have a basic project called airline with one app called flights. I create one model called Flight.

in a file called test.py I have:

from flights.models import Flight

f= Flight(origin="New York",destination="London", duration = 415)
f.save()

where do I place this file in order to run and update the database table? makemigrations and migrate were run successfully. Is there anything else that needs to be done to make the code run?

Upvotes: 1

Views: 62

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477210

You can define a data migration [Django-doc]. This is a migration you make yourself, for example to add/update/remove data.

You do this by first constructing a migration file with:

python manage.py makemigrations --empty flights

next in the migration file, you can define a function to run and to create the Flight object:

from django.db import migrations

def add_flight(apps, schema_editor):
    Flight = apps.get_model('flights', 'Flight')
    Flight.objects.create(origin='New York', destination='London', duration=415)

class Migration(migrations.Migration):

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

    operations = [
        migrations.RunPython(add_flight),
    ]

We load the class with apps.get_model('flights', 'Flight'). This will construct a Django model of the Flight at that moment of the migrations. If for example you later add an extra field to your Flight then, as long as that migration did not run, the Flight will not have that extra field.

Upvotes: 1

Related Questions