Skip to main content
 首页 » 编程设计

python之不使用固定装置的 Django 1.10 种子数据库

2025年05月04日42fff_TT

所以我查看了 documentation ,以及这个 SO question , 和 django-seed package ,但这些似乎都不适合我正在尝试做的事情。

基本上,我想通过外部 API 以编程方式为我的 Games 模型播种,但我能找到的所有信息似乎都依赖于先生成一个夹具,这似乎是一个不必要的步骤。

例如,在 Ruby/Rails 中,您可以直接写入 seed.rb 并以所需的方式为数据库播种。

如果 Django 中有类似的功能,还是我需要先从 API 生成夹具,然后导入它?

请您参考如下方法:

您可以为此使用数据迁移。首先为您的应用创建一个空迁移:

$ python manage.py makemigrations yourappname --empty 

在您的空迁移中,创建一个函数来加载您的数据并添加一个 migrations.RunPython 操作。这是来自 Django documentation on migrations 的版本的修改版本:

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)] 

如果您有大量简单数据,您可能会受益于批量创建方法:

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)] 

迁移具有自动包含在事务中的额外好处,因此您可以随时停止迁移并且不会使您的数据库处于不一致状态。