2015-12-08 57 views
0

這裏是我的模型:Django REST框架如何在JSON響應中刪除unicode前綴?

class Question(models.Model): 
    options = models.TextField() 

這裏是串行:

class QuestionSerializer(ModelSerializer): 
    class Meta: 
     model = Question 

這裏是視圖:

class QuestionView(ListAPIView): 
    queryset = Question.objects.all() 
    renderer_classes = (JSONRenderer,) 
    serializer_class = QuestionSerializer 

在數據庫內,可用的記錄是這樣的:

id options 
1 [u'opt1', u'opt2'] 

當請求API,這裏是返回的JSON:

{ 
    "id": 1, 
    "options": "[u'opt1', u'opt2']" 
} 

我的問題是如何保存的字符串以JSON格式和JSON格式檢索它沒有統一的前綴? (我需要支持Unicode字符,所以我不能簡單地轉換由用戶提交的字符串數據)


更新:這是我迄今發現的一個解決方案。使用django-jsonfield來定義你的領域:

from jsonfield import JSONField 

class Question(models.Model) 
    options = JSONField() 

然後,定義自定義序列字段:

from rest_framework import serializers 

class JsonField(serializers.Field): 
    def to_representation(self, value): 
     return value 

    def to_internal_value(self, data): 
     return data 

使用此字段中串行:

class QuestionSerializer(ModelSerializer): 
    options = JsonField() 

    class Meta: 
     model = Question 

現在,如果你嘗試存儲和然後從數據庫中檢索記錄,您應該得到一個JSON格式的字符串,而不使用unicode前綴。

由於Django的jsonfield正在尋找維護ATM,以防萬一它變得過時了,這裏是我使用的版本:

  • 的Django 1.8.7
  • Django的jsonfield 1.0.3
  • PostgresSQL 9.4.0.1
+0

檢查此答案https://stackoverflow.com/questions/34038367/i-am-sending-json-data-to-api-but-getting-unicode-json-data -whe-api-call-from-an/34039096#34039096 –

回答

0

使用UTF-8編碼unicode字符串。 Unicode的前綴將消失,該字符串將仍然支持Unicode字符:

>>> msg = u"Hello" 

>>> msg = msg.encode("utf-8") 

>>> msg 

'Hello' 

因爲你需要所有的值轉換成一個字典,你可能需要編寫一個函數來做到這一點。但它已被照顧在這裏:How to get string objects instead of Unicode ones from JSON in Python?

+0

不能這樣做,因爲我需要支持unicode – Cheng

+0

這是一個與django-rest-framework相關的問題。 'renderer_classes =(JSONRenderer,)'應該執行你所建議的IMO。但我不確定它爲什麼不起作用。 – Cheng

相關問題