Dar*_*one 1 python django django-fixtures
因此,我查看了文档以及这个SO问题以及django-seed软件包,但是这些似乎都不适合我想要的工作。
基本上,我想以编程方式Games从外部API 播种模型,但是我能找到的所有信息似乎都依赖于首先生成固定装置,这似乎是不必要的步骤。
例如,在Ruby / Rails中,您可以根据需要直接以seed.rb任何方式直接写入数据库并为数据库设置种子。
如果Django提供了类似的功能,还是我需要先从API生成固定装置,然后将其导入?
您可以为此使用数据迁移。首先为您的应用创建一个空迁移:
$ python manage.py makemigrations yourappname --empty
Run Code Online (Sandbox Code Playgroud)
在空迁移中,创建一个函数来加载数据并添加migrations.RunPython操作。这是Django文档中有关迁移的版本的修改版本:
from __future__ import unicode_literals
from django.db import migrations
def stream_from_api():
...
def load_data(apps, schema_editor):
# We can't import the Person model directly as it may be a newer
# version than this migration expects. We use the historical version.
Person = apps.get_model('yourappname', 'Person')
for item in stream_from_api():
person = Person(first=item['first'], last=item['last'], age=item['age'])
person.save()
class Migration(migrations.Migration):
dependencies = [('yourappname', '0009_something')]
operations = [migrations.RunPython(load_data)]
Run Code Online (Sandbox Code Playgroud)
如果您有很多简单的数据,则可以从批量创建方法中受益:
from __future__ import unicode_literals
from django.db import migrations
def stream_from_api():
...
def load_data(apps, schema_editor):
# We can't import the Person model directly as it may be a newer
# version than this migration expects. We use the historical version.
Person = apps.get_model('yourappname', 'Person')
def stream_people():
for item in stream_from_api():
yield Person(first=item['first'], last=item['last'], age=item['age'])
# Adjust (or remove) the batch size depending on your needs.
# You won't be able to use this method if your objects depend on one-another
Person.objects.bulk_create(stream_people(), batch_size=10000)
class Migration(migrations.Migration):
dependencies = [('yourappname', '0009_something')]
operations = [migrations.RunPython(load_data)]
Run Code Online (Sandbox Code Playgroud)
迁移具有自动封装在事务中的附加好处,因此您可以随时停止迁移,并且不会使数据库处于不一致的状态。
| 归档时间: |
|
| 查看次数: |
853 次 |
| 最近记录: |