Home > Blockchain >  How to automatically insert data in Django using Djangos ORM?
How to automatically insert data in Django using Djangos ORM?

Time:01-29

I am new to Django and have read the basic and advanced tutorial along with some parts of the documentation on migrations and data migrations: https://docs.djangoproject.com/en/4.0/topics/migrations/#data-migrations

Also, I have read about fixtures but this seems to be suitable only for initial data provision: https://docs.djangoproject.com/en/4.0/howto/initial-data/#providing-data-with-fixtures

The task I want to accomplish is to bulk insert data repeatedly from "outside" in a clean way using using Djangos ORM and all the benefits of migrations using a command line or other suitable interface such as a REST API.

So far, I haven't found a full example on how to do this because using the first option of data migration would require to touch a file everytime I insert/migrate new data.

Any hints on how to accomplish this or am I missing something?

Thanks in advance!

CodePudding user response:

You can create an empty migration with

python manage.py makemigrations --empty yourappname

Then define some functions with the data you want to fill like this:

from django.db import migrations

def create_estado(apps, schema_monitor):
    '''
    Create estado of empaque
    '''
    Estado = apps.get_model('empaques_app', 'Estado_empaque')

    Estado.objects.create(nombre='Bueno')
    Estado.objects.create(nombre='Dañado')
    Estado.objects.create(nombre='Reparando')

class Migration(migrations.Migration):

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

    operations = [
        migrations.RunPython(create_estado)
    ]

CodePudding user response:

I think you are missing the point of migrations. Use them if you want to alter a schema on your database, or if you want to insert some data once. For your case, you should use management commands.

  •  Tags:  
  • Related