Home > Software design >  Django return new property in json response
Django return new property in json response

Time:10-21

I have a view in Django that fetches some objects, adds new attribute to them and returns them as JSON response.

The code looks like this:

def stats(request):
    items = MyItem.objects.all().order_by('-id')

    for item in items:
        item.new_attribute = 10
        
    items_json = serializers.serialize('json', items)

    return HttpResponse(items_json, content_type='application/json')

The new_attribute is not visible in JSON response. How can I make it visible in JSON response? It can be accessed in templates normally with {{ item.new_attribute }}.

EDIT: I'm using default Django serializer (from django.core import serializers)

CodePudding user response:

Default serializer looks into fields defined in model. Thus, there are two options to resolve it:

  1. Add the attribute to your model MyItem
  2. Use a custom serializer to serialize your model with this dynamic attribute

Example of such serializer:

serializers.py

class MyItemSerializer(serializers.ModelSerializer):
    new_attribute = serializers.SerializerMethodField()

    def get_new_attribute(self, obj):
        if hasattr(obj, 'new_attribute'):
            return obj.new_attribute
        return None

    class Meta:
        model = MyItem
        fields = '__all__'

And then in views.py it will be:

items_json = serializers.MyItemSerializer(items, many=True).data

CodePudding user response:

Since you are reference serializers in your code, I assume that you are using Django REST Framework and have a class named MyItemSerializer. This class tells is used by serializers.serialize() to determine how to create the JSON string from your model objects. In order to add a new attribute to the JSON string, you need to add the attribute to this class.

  • Related