【问题标题】:Mongoengine serialize dictionary (with nested dicts)?Mongoengine 序列化字典(带有嵌套字典)?
【发布时间】:2017-08-21 10:50:40
【问题描述】:

我已经从 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) 就像一个魅力! :)

【问题讨论】:

    标签: dictionary serialization django-rest-framework restframeworkmongoengine


    【解决方案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)) - 它还有其他方法。

    【讨论】:

    • 感谢您的反馈。序列化器已经制作好了。可能应该让它更清楚一点。视图集是一个很好的和 EmbeddedDocumentListField!我现在试一试并更新。
    • 另外如前所述,如何将由上传文件制作的字典放入序列化程序中?那是主要部分。我已经在 POST 中进行上传了
    • @JamesBellaby 在您的视图中您指定了serializer_class = FileSerializer,对吗?您的视图集由一个 GenericView 和 mixins 组成,每个 REST 方法一个。当您将数据发布到该视图集时,它会从CreateModelMixin 调用create() 方法,该方法从serializer_class 属性构造您的序列化程序,将输入数据传递给它并调用seiralizer.is_valid(),它执行验证和serializer.save(),它将验证的数据保存到数据库:github.com/encode/django-rest-framework/blob/master/…
    • 这里可能有误会。我已经发送了一个上传文件的请求,然后读取该文件并将其切碎到字典(OP)中。这意味着我已经发送了一个请求,并且我正在使用 REST POST 方法处理文件以制作字典。那么我如何将字典获取到序列化程序。每次我尝试时它都说“无法获取 repr”我是否将 POST 方法中的 URL 称为“localhost/”?
    • 在作为 ModelViewSet 执行此操作时,由于更好的错误消息,它向我指出了根本问题。它是我的序列化程序Meta.model 类中的一种类型毕竟!哈哈感谢@BorisBurkov的帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-19
    • 2011-09-18
    • 2022-01-22
    • 2019-06-13
    • 2022-11-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多