如何在 yaml 中 Django 转储数据嵌套模型

how to Django dumpdata nested models in yaml

所以我有了这个很棒的 Django 应用程序,它让我很满意等等。 但现在的问题是,我想使用 dumpdata(或类似的东西)以 yaml 格式导出带有嵌套其他模型的模型。

假设我有两个模型,ProjectQuestions。每个 Project 都可以拥有自己的一组 Questions.

代码看起来像这样:

项目模型:

class Projects(SortableMixin):
    """
    Some docstring
    """
    slug = models.SlugField(
            _('slug'),
            help_text=_('Short name to address this projects from templates.'))
    # Basic fields
    object_id = models.PositiveIntegerField(blank=True, null=True)
    name = models.TextField(_('name'), help_text=_('The question.'))
    # Some other fields...
    question = models.ForeignKey(Question, null=True, blank=True)

问题模型:

class Question(SortableMixin):
    """
    Some docstring
    """
    slug = models.SlugField(
        _('slug'),
        help_text=_('Short name to address this question from templates.'))
    # Basic fields
    object_id = models.PositiveIntegerField(blank=True, null=True)
    name = models.TextField(_('name'), help_text=_('The question.'))
    input = models.TextField()

Project 模型有自己的应用程序,Questions 模型也有。 结构如下所示:

- Django
  - Apps
    - Project
    - Questions

每当我想导出数据库时,我都会执行以下操作:

./manage.py dumpdata --indent 4 --format yaml > dbdump.yaml

虽然这有效,而且我可以稍后使用 LoadData 导入它,但这不是我想要的,yaml 文件的输出看起来很糟糕。我想要一个漂亮的嵌套模型外观 yaml 文件以供审查,位于外观糟糕的文件下方:

项目部分:

-   model: project.projects
    pk: 1
    fields: {slug: "slugproject1", object_id: 10, name: "some project 1", question: ["slugquestion1"]}
-   model: project.projects
    pk: 2
    fields: {slug: "slugproject2", object_id: 11, name: "some project 2", question: ["slugquestion2"]}
-   model: project.projects
    pk: 3
    fields: {slug: "slugproject3", object_id: 12, name: "some project 3", question: ["slugquestion3"]}

问题部分:

-   model: question.question
    pk: 1
    fields: {slug: "slugquestion1", object_id: 100, name: "some question 1", input: "q1"}
-   model: question.question
    pk: 1
    fields: {slug: "slugquestion2", object_id: 200, name: "some question 2", input: "q2"}
-   model: question.question
    pk: 1
    fields: {slug: "slugquestion3", object_id: 300, name: "some question 3", input: "q3"}

我真正想要的是像这样导出 yaml 文件:

-   model: project.projects
    pk: 1
    fields: {
        slug: "slugproject1", 
        object_id: 10, 
        name: "some project 1", 
        questions: {
            model: question.question
            pk: 1
            fields: {
                 slug: "slugquestion1"
                 object_id: 100
                 name: "some question 1"
                 input: "q1"
            }            
        }
    }
-   model: project.projects
    pk: 2
    fields: {
        slug: "slugproject2", 
        object_id: 11, 
        name: "some project 2", 
        questions: {
            model: question.question
            pk: 2
            fields: {
                 slug: "slugquestion2"
                 object_id: 200
                 name: "some question 2"
                 input: "q2"
            }            
        }
    }
-   model: project.projects
    pk: 3
    fields: {
        slug: "slugproject3", 
        object_id: 13, 
        name: "some project 3", 
        questions: {
            model: question.question
            pk: 3
            fields: {
                 slug: "slugquestion3"
                 object_id: 300
                 name: "some question 3"
                 input: "q3"
            }            
        }
    }

为了实现这一点,我在项目中实现了一个自定义序列化程序:

- Django
  - Apps
    - Project
      - Management
        - Commands
          - test.py
    - Questions

代码如下:

from django.core.management.base import BaseCommand, CommandError
from apps.project import Projects
from apps.questions import Question
from rest_framework import serializers
import yaml


class QuestionSerialier(serializers.ModelSerializer):
    class Meta:
        model = Question
        fields = ('pk', 'slug', 'object_id', 'name', 'input')


class ProjectsSerializer(serializers.ModelSerializer):
    questions = QuestionSerialier(many=True, read_only=True)

    class Meta:
        model = Projects
        fields = ('pk', 'slug','object_id', 'name', 'questions')


class Command(BaseCommand):
    help = ''

    def add_arguments(self, parser):
        pass

    def handle(self, *args, **options):

        with open('result.yaml', 'w') as yaml_file:
            for i in Projects.objects.filter():
                yaml.dump(ProjectsSerializer(i).data, 
                                yaml_file,
                                default_flow_style=False,
                                allow_unicode=False,
                                encoding=None)

我可以 运行 代码 运行ning:

./manage.py test

只有这样才能导出我的模型:

- project: 1
  pk: 1
  slug: "slugproject1"
  object_id: 10
  name: "some project 1"
  questions:
  - !!python/object/apply:collections.OrderedDict
    - - - pk
      - - slug
      - - object_id
      - - name
      - - input
- project: 2
  pk: 2
  slug: "slugproject2"
  object_id: 11
  name: "some project 2"
  questions:
  - !!python/object/apply:collections.OrderedDict
    - - - pk
      - - slug
      - - object_id
      - - name
      - - input
- project: 3
  pk: 3
  slug: "slugproject3"
  object_id: 12
  name: "some project 3"
  questions:
  - !!python/object/apply:collections.OrderedDict
    - - - pk
      - - slug
      - - object_id
      - - name
      - - input

如您所见,以上内容不可用于导入,甚至不可读导出...

你们能否为我指明正确的方向,了解如何在 Django 中实现嵌套模型转储数据 yaml 导出?

谢谢!

所以我想出了如何处理 export/import。

为了导出正确的 yaml 文件格式,我执行了以下操作:

...
class Command(BaseCommand):

def handle(self, *args, **options):
    with open('result.yaml', 'w') as yaml_file:
        model = serializer.Meta.model
        json_object = []
        json_data = json.dumps(serializer(model_data).data)
        json_object.append(json.loads(json_data))

        yaml.dump(
            json_object,
            yaml_file,
            default_flow_style=False,
            allow_unicode=False,
            encoding=None
        )

这将导出到正确的 yaml 文件。

然后为了导入 yaml 文件,我执行了以下操作:

...
class Command(BaseCommand):
    def handle(self, *args, **options):
        with open('result.yaml', 'r') as yaml_file:
            yaml_list = yaml.load(yaml_file.read())
            for data in yaml_list:
                ...process file

就是这样!