1

我已经从 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。

已回答

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

4

1 回答 1

1

詹姆士!

验证传入 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))- 它有其他方法。

于 2017-08-21T22:17:47.207 回答