Django:0x7feaac2761d0上的<django.utils.functional .__ proxy__对象>不是JSON可序列化的

mas*_*iny 10 python django serialization

我在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)
Run Code Online (Sandbox Code Playgroud)

基于county_id我正在过滤状态名称并尝试转换为json格式,以便我可以更新选择框.

但是我这样做了.

<django.utils.functional.__proxy__ object at 0x7feaac2761d0> is not JSON serializable
Run Code Online (Sandbox Code Playgroud)

这是我的看法.

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") 
Run Code Online (Sandbox Code Playgroud)

请帮我解决这个错误.

更新

我也是这样试过的

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)
Run Code Online (Sandbox Code Playgroud)

有了这个观点

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)
Run Code Online (Sandbox Code Playgroud)

nik*_*ela 18

django.utils.functional.__proxy__对象是一个懒惰的翻译.Django文档说,使用延迟转换作为参数调用unicode()将在当前语言环境中生成一个Unicode字符串(https://docs.djangoproject.com/en/dev/ref/unicode/#translated-strings).翻译完成后,序列化更有意义.


dan*_*van 1

如果您运行的是旧版本,django则无法QuerySets进行开箱即用的序列化。尝试

json_models = serializers.serialize("json", list(get_related_subcategory))
Run Code Online (Sandbox Code Playgroud)

可能还值得检查一下是否get_related_subcategory不为空。django您运行的是哪个版本?