2
I want to return the result in JSON
following this format:
{"cadastros": [
{"id": 1, "STATUS": true, "pessoas": [], "podeEscrever": true},
{"id": 2, "STATUS": false, "pessoas": ['Maria', 'Ana'], "podeEscrever": true},
], 'principal': true}
py.models:
class MyModel(models.Model):
status = models.BooleanField()
pessoas = models.ManyToManyField(Pessoa, blank=True)
podeescrever = models.BooleanField()
See that in format JSON
exists podeEscrever
uppercase letter, so the result should follow this format as well.
The main idea is to use the library simplejson
to manipulate the result and return the JSON
in the desired format.
py views.:
def minha_views(request):
p = Pessoa.objects.values()
data = simplejson.dumps(p)
# aqui seria formatado
return HttpResponse(data, content_type='application/json; charset=utf8')
My difficulty is in formatting the JSON
, i can return the results of the query directly to JSON
, but I don’t know how to manipulate to add new keys and change the field name podeescrever
for podeEscrever
.
Another thing that’s happening is that the field pessoas
that is ManytoManyField
does not return in the JSON
if empty, the correct one was to return with an empty list []
if there are no items.
It does not seem to be difficult to perform this procedure, someone knows how to solve this problem?
In this case the real model is great, but doing it this way seems more efficient. I installed the new version of
simplejson
because I was having a problem withdecimal
, I just can’t remember now if it was with thejson
or withsimplejson
of the project. In relation to theprefetch_related
I have not yet understood how it works, whenever you consult a fieldManyToMany
(p.pessoas.all()
) should I wearprefetch_related
to improve performance?– Paulo
@Orion It’s not just one
ManyToMany
, but with any field that makes a Join between tables (ex.:ForeignKey
). Let’s say the modelA
have a fieldb
referencing a modelB
. Let’s also say thatA
has 1000 lines, each referencing a separate line ofB
(also 1000). If you dofor a in A.objects.all(): print (a.b)
Django’s gonna do it 1001 BD! But withfor a in A.objects.all().prefetch_related("b"): print (a.b)
he’ll just do 2. I’m not sure the same goes for the call fromvalues
, but I think so (I would have to test).– mgibsonbr