【问题标题】:python+django trying to serialize mongoengine documents to json but getting only arrays of fields namespython+django 尝试将 mongoengine 文档序列化为 json 但只获取字段名称数组
【发布时间】:2016-12-15 22:50:21
【问题描述】:

我有以下模型:

class Estados(Document):
    Nome = StringField(max_length = 20, required=True)
    Sigla = StringField(max_length = 2, required=True)
    Cidades = ListField(StringField)

当我查询它时,用这个方法:

from django.http import HttpRequest
from app.models import Estados
from django.http import HttpResponse
from bson.json_util import dumps, default
import sys
import mongoengine

def BuscarEstados(request):
    erro = None
    dados = []
    try:
        dados = Estados.objects.exclude('Cidades').all()
    except Exception as e:
        erro = 'Solicicação inválida: ' + str(e)

    return HttpResponse(dumps({ 'erro': erro, 'dados': dados}, default=default))

我只得到带有字段名称的数组:

{"dados": [["id", "Nome", "Sigla", "Cidades"], ["id", "Nome", "Sigla", "Cidades"], ["id", "Nome", "Sigla", "Cidades"], ["id", "Nome", "Sigla", "Cidades"], ["id", "Nome", "Sigla", "Cidades"], ["id", "Nome", "Sigla", "Cidades"], ["id", "Nome", "Sigla", "Cidades"], ["id", "Nome", "Sigla", "Cidades"], ["id", "Nome", "Sigla", "Cidades"], ["id", "Nome", "Sigla", "Cidades"], ["id", "Nome", "Sigla", "Cidades"], ["id", "Nome", "Sigla", "Cidades"], ["id", "Nome", "Sigla", "Cidades"], ["id", "Nome", "Sigla", "Cidades"], ["id", "Nome", "Sigla", "Cidades"], ["id", "Nome", "Sigla", "Cidades"], ["id", "Nome", "Sigla", "Cidades"], ["id", "Nome", "Sigla", "Cidades"], ["id", "Nome", "Sigla", "Cidades"], ["id", "Nome", "Sigla", "Cidades"], ["id", "Nome", "Sigla", "Cidades"], ["id", "Nome", "Sigla", "Cidades"], ["id", "Nome", "Sigla", "Cidades"], ["id", "Nome", "Sigla", "Cidades"], ["id", "Nome", "Sigla", "Cidades"], ["id", "Nome", "Sigla", "Cidades"], ["id", "Nome", "Sigla", "Cidades"]], "erro": null}

请问,我做错了什么?

我正在使用 Django 1.10.4、pymongo 3.4.0、mongoengine 0.11.0 和 python 3.5

【问题讨论】:

    标签: python django mongodb django-models mongoengine


    【解决方案1】:

    我找到了解决方案...不幸的是 MongoEngine 的文档仍在增长...

    他们为文档提供了一个 to_json() 方法。

    所以:

    dados = Estados.objects.exclude('Cidades').all().to_json()
    

    【讨论】:

      猜你喜欢
      • 2021-12-08
      • 1970-01-01
      • 1970-01-01
      • 2020-03-15
      • 2018-05-06
      • 2021-05-27
      • 2015-04-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多