3

I need to populate a database table, and according this post the proper way to do this is using a data migration.

I have an aux function, lets call it get_my_values that returns a dictionary of dictionaries with the following shape:

{
    origin1: { key2: value2, key3: value3, ..., keyN: valueN },
    origin2: { key1: value1, key3: value3, ..., keyN: valueN },
    ...
    originN: { key1: value1, key2: value2, ..., keyN-1: valueN-1 },
}

For e.g:

{
  'ABC': { 'DEF': 1, 'GHI': 2 },
  'DEF': { 'ABC': 1, 'GHI': 3 },
  'GHI': { 'ABC': 2, 'DEF': 3 },
}

And the table that I want to populate have this shape:

ORIGIN | 'ABC'  | 'DEF' | 'GHI' |
 char  |  float | float | float |

So, following this post I created the following migration:

from django.db import migrations
from myapp.utils import get_my_values


def populate_my_table(apps, schema_editor):
  Data = apps.get_model('myapp', 'Table')
  my_data_dict = get_my_values()
  for origin in my_data_dict.keys():
    # insert into Data.origin the current origin
    # if the Data.origin == Data.column, insert in this column the value 0
    # else, insert in each Data.column, the corresponding value from my_data_dict[origin]['column']


class Migration(migrations.Migration):

    dependencies = [
        ('myapp', 'the_table_migration'),
    ]

    operations = [
      migrations.RunPython(populate_my_table),
    ]

As you can see, I wrote a pseudo-code to populate it. But i'm struggling to actually turn into real code.
In the end, I expect records like this:

ORIGIN | ABC | DEF | GHI |
 ABC   | 0.0 | 1.0 | 2.0 |
 DEF   | 1.0 | 0.0 | 3.0 |
 GHI   | 2.0 | 3.0 | 0.0 |
João Ramires
  • 723
  • 10
  • 23

1 Answers1

3
def populate_my_table(apps, schema_editor):
    Data = apps.get_model('myapp', 'Table')
    my_data_dict = get_my_values()
    for origin, values in my_data_dict.items():
        data = {'origin': origin, origin: 0.0}
        data.update(values)
        Data.objects.create(**data)
Jason Yang
  • 196
  • 3