2016-04-28 71 views
1

我道歉,新的Django。我一直在搜索文檔,一直沒有找到答案。Django串行器顯示模型字段作爲字典

我有一個模型「富」,有一個字段「欄」,這是一個字典,我存儲爲JSON在TextField中。我想要一個GET請求來顯示這個字段作爲字典,但是當我發出請求時,字典顯示爲JSON格式的單個字符串。

總結我的代碼:

型號:

class Foo(models.Model): 
    bar = models.TextField(blank=True, default="{}") 
    def getBar(self): 
     return json.loads(bar) 

串行器:

class FooSerializer(serializers.ModelSerializer): 
    class Meta: 
     model = Foo 
     fields = ("bar") 
     read_only_fields = ("bar") 
    def create(self, data): 
     return Foo.objects.create(**data) 

觀點:

class FooList(generics.ListAPIView): 
    queryset = [] 
    for foo in Foo.objects.all(): 
     foo.bar = json.loads(foo.bar) 
     # Printing type of foo.bar here gives "type <dict>" 
     queryset.append(foo) 
    serializer_class = FooSerializer 

謝謝!

回答

1

您可以將SerializerMethodField添加到您的ModelSerializer類象下面這樣:

class FooSerializer(serializers.ModelSerializer): 
    class Meta: 
     model = Foo 
     fields = ('bar',) 
     read_only_fields = ('bar',) # Not required, because 
            # SerializerMethodField is read-only already 

    bar = serializers.SerializerMethodField('get_bar_dict') 

    def get_bar_dict(self, obj): 
     return json.loads(obj.bar) # This gets the dict and returns it 
            # to the SerializerMethodField above 

    # Below is the rest of your code that I didn't touch 
    def create(self, data): 
     return Foo.objects.create(**data) 
+0

完美工作,感謝您的鏈接到文檔! – Kieran