我在 django 序列化中遇到问题
这是我的国家模型
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)
基于county_id,我正在过滤州名并尝试转换为json格式,以便我可以更新选择框。
但我正在这样做。
<django.utils.functional.__proxy__ object at 0x7feaac2761d0> is not JSON serializable
以下是我的看法。
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")
请帮我解决这个错误。
更新
我也试过这样
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)
有了这个观点
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)