2012-11-06 3 views
8

Decimal 객체가 포함 된 쿼리 집합이 있습니다. 이 데이터를 줄을 따라 json 덤프에 전달하고 싶습니다.Django json에 Decimal 객체 전달 방법

ql = Product.objects.values_list('length', 'width').get(id=product_id) 
data = simplejson.dumps(ql) 

TypeError: Decimal('62.20') is not JSON serializable 

이 값을 json에 어떻게 전달해야합니까? 물론 문자열에 값을 캐스팅 할 수는 있지만 좋은 해결책은 아닌 것 같습니다.

도움을 주시면 감사하겠습니다.

답변

20

장고는 이미 인코더를 포함하고 있습니다. cls 매개 변수로 전달하십시오.

data = simplejson.dumps(ql, cls=DjangoJSONEncoder) 
+1

차가움. 그건 속임수 야. –

+0

여기에 문제가 있습니다. 컨텍스트를 2 소수점으로 설정했지만 전체 8-10 점을 계속 덤핑합니다. 여기서 내가 놓친 게 뭐야? – Cheluis

+2

'ValuesQuerySet'을 반환하는'.values' 또는'.values_list'를 사용할 때 쿼리 세트를 직렬화하는 경우'TypeError' 오류가 발생합니다. 예를 들어 위와 같이 사용하려면 목록에 강제로 넣으십시오 :'data = simplejson.dumps (list (ql), cls = DjangoJSONEncoder)' –

1

여기이 질문에 발견 대답입니다 : Python JSON serialize a Decimal object

어떻게 json.JSONEncoder를 서브 클래스에 대한? 귀하의 경우에는


class DecimalEncoder(simplejson.JSONEncoder): 
    def _iterencode(self, o, markers=None): 
     if isinstance(o, decimal.Decimal): 
      # wanted a simple yield str(o) in the next line, 
      # but that would mean a yield on the line with super(...), 
      # which wouldn't work (see my comment below), so... 
      return (str(o) for o in [o]) 
     return super(DecimalEncoder, self)._iterencode(o, markers) 
, 당신은 다음과 같이 사용합니다 : django.core.serializers.json.DjangoJSONEncoder : 소수뿐만 아니라 날짜 시간 처리 할 수있는 것보다

data = simplejson.dumps(ql, cls=DecimalEncoder) 
+0

이 방법으로도 여전히 동일한 오류가 발생합니다. –