【问题标题】:How can I make a fixture out of QuerySet in django?如何在 django 中使用 QuerySet 制作固定装置?
【发布时间】:2012-07-19 18:28:20
【问题描述】:

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

【问题讨论】:

    标签: django django-models django-fixtures


    【解决方案1】:

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

    from django.core import serializers
    data = serializers.serialize("json", SomeModel.objects.all())
    

    然后将data 写入文件。

    【讨论】:

      【解决方案2】:

      以下步骤将帮助完成解决方案,为创建各种查询集的固定装置提供支持。

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

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

      from django.core import serializers
      
      for obj in serializers.deserialize('json', open('output.json').read()):
          obj.save()
      

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

      import collections
      
      app_list = collections.OrderedDict()
      

      【讨论】:

        【解决方案3】:

        如果您想将 json 数据直接保存到文件中,可以使用:

        from django.core import serializers
        
        
        data = YourModel.objects.all()
        with open("fixtures.json", "w") as out:
            serializers.serialize("json", data, stream=out)
        

        【讨论】:

          【解决方案4】:

          我不确定您所说的“外部模型关系”是什么意思,也许举个例子会有所帮助,但是您可以将 dumpdata 传递给您感兴趣的模型...

          manage.py dumpdata --help
          Usage: ./manage.py dumpdata [options] [appname appname.ModelName ...]
          

          还有排除开关:

          -e EXCLUDE, --exclude=EXCLUDE
                              An appname or appname.ModelName to exclude (use
                              multiple --exclude to exclude multiple apps/models).
          

          【讨论】:

          • 我只是说转储不需要跟踪与被转储模型相关的模型。
          猜你喜欢
          • 1970-01-01
          • 2021-02-08
          • 2014-12-25
          • 2015-07-28
          • 2019-10-31
          • 2014-01-10
          • 1970-01-01
          • 2022-11-17
          • 2012-06-23
          相关资源
          最近更新 更多