我需要填充一个数据库表,根据这篇文章,正确的方法是使用数据迁移。我有一个 aux 函数,我们称之为get_my_values,它返回具有以下形状的字典字典:{ origin1: { key2: value2, key3: value3, ..., keyN: valueN }, origin2: { key1: value1, key3: value3, ..., keyN: valueN }, ... originN: { key1: value1, key2: value2, ..., keyN-1: valueN-1 },}例如:{ 'ABC': { 'DEF': 1, 'GHI': 2 }, 'DEF': { 'ABC': 1, 'GHI': 3 }, 'GHI': { 'ABC': 2, 'DEF': 3 },}我要填充的表格具有以下形状:ORIGIN | 'ABC' | 'DEF' | 'GHI' | char | float | float | float |因此,在这篇文章之后,我创建了以下迁移:from django.db import migrationsfrom myapp.utils import get_my_valuesdef 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), ]如您所见,我编写了一个伪代码来填充它。但我正在努力真正变成真正的代码。最后,我期望这样的记录: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 |
1 回答
HUWWW
TA贡献1874条经验 获得超12个赞
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)
添加回答
举报
0/150
提交
取消