Kieran
Kieran

Reputation: 133

Django Serializer Display Model Field as Dictionary

I apologize, new to Django. I've been scouring the documentation and haven't been able to find the answer to this.

I have a model "Foo" that has a field "bar", which is a dictionary I store as JSON in a TextField. I want a GET request to display this field as a dictionary, but when I make the request, the dictionary is displayed as a single string in JSON format.

To summarize my code:

models:

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

Serializers:

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

views:

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

Thanks!

Upvotes: 1

Views: 1638

Answers (1)

bakkal
bakkal

Reputation: 55448

You can add a SerializerMethodField to your ModelSerializer class like below:

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)

Upvotes: 1

Related Questions