如何在django中使用QuerySet创建一个fixture?

pie*_*zym 10 django django-models django-fixtures

Django dumpdata命令被破坏,因为它不支持任何合理的方法来缩小转储的数据量.我需要创建一个包含各种查询集的夹具(我不需要关心从外部模型关系中转储对象).限制这些查询集的项目数量,例如django-test-utils makefixture是不够的.试图通过使用具有自定义管理器的代理模型来实现这一点,但这种方法不起作用 - dumpdata省略了代理模型(这是合理的).

Ahs*_*san 33

如果dumpdata不起作用,您可以通过Django Serializing数据执行相同的操作.

from django.core import serializers
data = serializers.serialize("json", SomeModel.objects.all())
Run Code Online (Sandbox Code Playgroud)

然后写data一个文件.

  • 优秀!非常感谢! (2认同)

Bha*_*aaj 8

以下步骤将有助于使解决方案完整,并支持创建各种查询集的夹具

from django.core import serializers
from django.core.management.commands.dumpdata import sort_dependencies

app_list = {}

# Add all your querysets here. The key for the dictionary can be just a 
# unique dummy string (A safe hack after reading django code)
app_list['app1_name'] = FirstModel.objects.all()
app_list['app2_name'] = SecondModel.objects.all()

# The sort_dependencies will ensure that the models are sorted so that
# those with foreign keys are taken care. If SecondModel has a fk to FirstModel,
# then sort_dependencies will take care of the ordering in the json file so that
# FirstModel comes first in the fixture thus preventing ambiguity when reloading
data = serializers.serialize("json", sort_dependencies(app_list.items()))
f = open('output.json', 'w')
f.write(data)
f.close()
Run Code Online (Sandbox Code Playgroud)

现在输出将在output.json文件中可用。要从 json 文件重建模型:

from django.core import serializers

for obj in serializers.deserialize('json', open('output.json').read()):
    obj.save()
Run Code Online (Sandbox Code Playgroud)

编辑:奇怪的是, sort_dependencies 没有按预期工作。所以我最终使用了 pythonordereddict 并自己决定了顺序。

import collections

app_list = collections.OrderedDict()
Run Code Online (Sandbox Code Playgroud)