mardi 12 août 2014

python - Django - meilleure méthode pour sérialiser queryset en format JSON - Stack Overflow


I was trying two methods to serialize the field attribute_value of a queryset into JSON, and the fastest was not the one I tought it would. The field is an HSTORE field that is already formated for JSON


For instance:


print feature.attribute_value
>>>{"NOM": "Saguenay - Lac-Saint-Jean", "CODE": "45", "id": "0", "integer": "5"}

First method:


features_selected = Feature.objects.filter(shapefile__pk=shapefile_id).order_by("id")
data = [feature.attribute_value for feature in features_selected]
jsonData= json.dumps(data)

Second method:


features_selected = Feature.objects.filter(shapefile__pk=shapefile_id).order_by("id").values_list("attribute_value", flat=True)
jsonData= json.dumps(list(features_selected))

I tought the second method would be faster because only the field "attribute_value" is queryed instead of all (*) other fields in the first one, but the first was a little faster. I would like to know why, and if there could be a better way to serialize a queryset.



I was trying two methods to serialize the field attribute_value of a queryset into JSON, and the fastest was not the one I tought it would. The field is an HSTORE field that is already formated for JSON


For instance:


print feature.attribute_value
>>>{"NOM": "Saguenay - Lac-Saint-Jean", "CODE": "45", "id": "0", "integer": "5"}

First method:


features_selected = Feature.objects.filter(shapefile__pk=shapefile_id).order_by("id")
data = [feature.attribute_value for feature in features_selected]
jsonData= json.dumps(data)

Second method:


features_selected = Feature.objects.filter(shapefile__pk=shapefile_id).order_by("id").values_list("attribute_value", flat=True)
jsonData= json.dumps(list(features_selected))

I tought the second method would be faster because only the field "attribute_value" is queryed instead of all (*) other fields in the first one, but the first was a little faster. I would like to know why, and if there could be a better way to serialize a queryset.


0 commentaires:

Enregistrer un commentaire