djangodjango-modelsdjango-fixtures

Django fixture append to existing data


I have a table which contains some data already. Can a fixture be created with new data records and be appended to the existing data in the table, without specifying a pk explicitly?


Solution

  • If you want to use fixtures, you can create a Migration file in the corresponding app:

    from django.db import migrations, models
    
    
    def add_fixtures(apps, schema_editor):
        Model = apps.get_model("app_name", "model_name")  # You must replace app_name and model_name with your values
        db_alias = schema_editor.connection.alias
        # Now you can create some instances like this (you can omit the pk):
        Model.objects.using(db_alias).create(**your_data)
    
    
    def remove_fixtures(apps, schema_editor):
        # Reverses the action (needed for compatibility)
        Model = apps.get_model("app_name", "model_name")  # You must replace app_name and model_name with your values
        db_alias = schema_editor.connection.alias
        # Now you must delete the instances you created earlier, for example:
        Model.objects.using(db_alias).filter(id=1).delete()
    
    
    class Migration(migrations.Migration):
        dependencies = [
           # You must insert the last migration of the app, for example: ('app_name', '000x_migration_name')
        ]
        
        operations = [
           migrations.RunPython(add_fixtures, remove_fixtures)
        ]
    

    Otherwise you could simply creates new records with a script and run it in the console:

    # First obtains your data from a dictionary or maybe parsing a file (you can omit the pk)
    data_list = [{'example': 1}, {'example': 2}]
    
    for data in data_list:
       YourModelName.objects.create(**data)  # You must replace YourModelName with the name of your model
    

    Finally you could also use SQL to insert the data directly into the database.