简体   繁体   中英

python+django trying to serialize mongoengine documents to json but getting only arrays of fields names

I have the folowing model:

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

When I'm querying it, with this method:

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))

I get only arrays with the fields names:

{"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}

Please, what I'm doing wrong?

I'm using Django 1.10.4, pymongo 3.4.0, mongoengine 0.11.0 and python 3.5

I found the solution... Unfortunatelly the MongoEngine's documentation is still growing...

They provided a method to_json() to the documents.

So:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM