I am getting a problem in django serialization
Here is my model for the state
class State(models.Model):
class Translation(translation.Translation):
name = models.CharField(max_length=64)
capital = models.ForeignKey('City', related_name="state_capital", null=True)
country = models.ForeignKey(Country, related_name="state_country", null=True)
latitude = models.DecimalField(max_digits=9, decimal_places=6, default=Decimal("0.0"))
longitude = models.DecimalField(max_digits=9, decimal_places=6, default=Decimal("0.0"))
code = models.CharField(max_length=2)
Based on county_id i am filtering the states name and tried to convert in json format so that i can update the select box .
But I am getting while doing this .
<django.utils.functional.__proxy__ object at 0x7feaac2761d0> is not JSON serializable
Here is my views .
def get_getstate(request):
catid = request.GET['catid']
get_related_subcategory = State.objects.filter(country_id = catid)
json_models = serializers.serialize("json", get_related_subcategory)
return HttpResponse(json_models, mimetype="application/javascript")
Please help me outto solve this error .
Update
I also tried like this
from django.core.serializers.json import Serializer as JSONSerializer
import decimal
import json
class DecimalEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, decimal.Decimal):
return '%.2f' % obj # Display Decimal obj as float
return json.JSONEncoder.default(self, obj)
class DecimalSerializer(JSONSerializer):
def end_serialization(self):
self.options.pop('stream', None)
self.options.pop('fields', None)
json.dump(self.objects, self.stream, cls=DecimalEncoder, **self.options)
With this view
def get_getstate(request):
catid = request.GET['catid']
get_related_subcategory = State.objects.filter(country_id = catid)
my_serializer = DecimalSerializer()
print my_serializer.serialize(get_related_subcategory, indent=4)
django.utils.functional.__proxy__
object is a lazy translation. Django documentation says that calling unicode() with the lazy translation as the argument will generate a Unicode string in the current locale (https://docs.djangoproject.com/en/dev/ref/unicode/#translated-strings). When the translation is done, serialization makes more sense.
If you're running an older version of django
then you can't serialize QuerySets
out-of-the-box. Try
json_models = serializers.serialize("json", list(get_related_subcategory))
It might also be worth checking that get_related_subcategory
isn't empty. Which version of django
are you running?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With