<p>Django的方法是使用<a href="https://docs.djangoproject.com/en/1.8/topics/migrations/#data-migrations" rel="nofollow">Data Migrations</a>。这是绝对建议超过夹具(我认为主要用于测试数据)</p>
<p>基本上,您将进行模式迁移,您将在其中定义模型、字段等。在创建所有必要的模型以保存数据之后,您将创建一个额外的迁移,您将在其中运行类似于<code>Model.objects.create(field1='value1')</code>的代码。你知道吗</p>
<p>我发现<a href="https://realpython.com/blog/python/data-migrations/" rel="nofollow">this guide</a>对理解有很大帮助。下面是其中的示例:</p>
<pre><code># encoding: utf8
from django.db import models, migrations
from datetime import date
def load_data(apps, schema_editor):
PriceHistory = apps.get_model("historical_data", "PriceHistory")
PriceHistory(date=date(2013,11,29),
price=1234.00,
volume=354564,
total_btc=12054375,
).save()
PriceHistory(date=date(2012,11,29),
price=12.15,
volume=187947,
total_btc=10504650,
).save()
class Migration(migrations.Migration):
dependencies = [
('historical_data', '0002_auto_20140710_0810'),
]
operations = [
migrations.RunPython(load_data)
]
</code></pre>
<p>请注意,与模式迁移的唯一区别是<code>migrations.RunPython</code>调用一个自定义函数,该函数创建您想要的任何数据。你知道吗</p>
<p>对于South来说,这曾经是一个难题,但是由于迁移包含在vanilla Django的1.7版本中(与South是同一个开发人员),这非常容易,这要感谢在上述迁移中生成的直接代码。你知道吗</p>