Mongoengine 序列化字典(带嵌套字典)?

Mongoengine serialize dictionary (with nested dicts)?

我在 Django 中根据上传的文件创建了一个字典。

该词典有一个嵌套的词典列表:

file = {"name": "filename", "sections": [{"section_name": "string", "lines": [{line_number: 0, "line"; "data"}]}], "etc": "etc"}

该模型也代表字典深度。

class Line(EmbeddedDocument):
    line_number = IntField()
    line = StringField()
    definition = ReferenceField(Definition)


class Section(EmbeddedDocument):
    section_name = StringField()
    lines = EmbeddedDocumentListField(Line))


class File(Document):
    name = StringField()
    sections = EmbeddedDocumentListField(Section))
    created_on = DateTimeField()
    created_by = StringField()
    modified_on = DateTimeField()
    modified_by = StringField()

POST 中,我将文件分成上面的 Dict(该文件是一个简单的文本文件):

file= {}
with open(os.path.join(path, filename + ".txt"), 'r') as temp_file:
    filelines = temp_file.readlines()
    sections = []
    section = {}
    lines = []
    for i, l in enumerate(filelines):
        if i == 0:
            section["section_name"] = "Top"
        elif '*' in l:
            if l.index('*') == 0 and '*' not in lines[len(lines) - 2"line"]:
                section["lines"] = lines
                lines = []
                sections.append(section)
                section = dict()
                section["section_name"] = filelines[i + 1][1:-2]
   line = {"line_number": i + 1, "line": l}
   lines.append(line)
   section['lines'] = lines
   sections.append(section)
   file["name"] = filename
   file["sections"] = sections

我最终会把它整理好。 生成字典后,如何使用序列化程序对其进行序列化?

是否可以将其插入到序列化程序中?

如果不是,我如何通过验证将其全部放入数据库?

我试过 json.dumps()JsonRequst() 然后将它们放入序列化器的 data= 但得到 Unable to get repr for <class '....'>

我是 Django 的新手,MongoDB 所以如果您需要更多信息,我可以提供:)

谢谢!

更新

按照答案中的建议将模型的列表字段更改为 EmbeddedDocumentListField。

已回答

感谢鲍里斯在下面的建议,它指出了一个我最初没有得到的错误。我有一个错字,将字典直接传递给 FileSerializer(data=file) 就像一个魅力! :)

詹姆斯!

验证传入的 JSON 是否符合您指定的 Mongoengine 文档架构的最简单方法是使用 DRF-Mongoengine 的 DocumentSerializer.

基本上,您需要做的就是创建一个序列化程序

serializers.py

import rest_framework_mongoengine

class FileSerializer(rest_framework_mongoengine.DocumentSerializer):
    class Meta:
        fields = '__all__'
        model = File

那么您需要一个视图或视图集来使用此序列化程序来响应 GET/POST/PUT/DELETE 请求。

views.py

from rest_framework_mongoengine import viewsets

class FileViewSet(viewsets.ModelViewSet):
    lookup_field = 'id'
    serializer_class = FileSerializer

    def get_queryset(self):
        return File.objects.all()

并使用路由器注册此视图集

urls.py

from rest_framework import routers

# this is DRF router for REST API viewsets
router = routers.DefaultRouter()

# register REST API endpoints with DRF router
router.register(r'file', FileViewSet, r"file")

我还建议使用 EmbeddedDocumentListField 而不是 ListField(EmbeddedDocumentField(Section)) - 它有其他方法。