1

I would like to get JSON data on my backend without tying it to a model. For example, in json data like this I want access to quantity but don't want it tied to any model.

{
  "email": "some@gmail.com"
  "quantity": 5,
  "profile": {
      "telephone_number": "333333333"
  }
}

My serializer:

class PaymentSerializer (serializers.ModelSerializer):
    profile = UserProfilePaymentSerializer()
    # subscription = UserSubscriptionSerializer()

    class Meta:
        model = User
        fields = ('email', 'profile',)

    def create(self, validated_data):
        profile_data = validated_data.pop('profile')
        user = AuthUser.objects.create(**validated_data)
        Profile.objects.create(user=user, **profile_data)
        return user

    def update (self, instance, validated_data):
        instance.quantity = validated_data.get('quantity', instance.quantity)
        print instance.quantity
        return instance

When I send a PATCH request, I get an error

'User' object has no attribute 'quantity'

Anthony
  • 33,838
  • 42
  • 169
  • 278

3 Answers3

0

you can use json

import json
json.loads('{ "email": "some@gmail.com","quantity": 5,"profile": {"telephone_number": "333333333"}}')[u'quantity']

I think you can use simple json too (not tested):

from urllib import urlopen
import simplejson as json

url = urlopen('yourURL').read()
url = json.loads(url)

print url.get('quantity')
JoseM LM
  • 373
  • 1
  • 8
0

AFAIK, passing an extra data to ModelSerializer and attribute missing in model will throw as you stated. If you want to have extra attribute which is not present in model, restore_object needs to overriden.

Few examples GitHub Issue and similar SO Answer

Kracekumar
  • 19,457
  • 10
  • 47
  • 56
0

You could try something like this:

class PaymentSerializer (serializers.ModelSerializer):
    ...

    quantity = serializers.SerializerMethodField('get_quantity')

    class Meta:
        model = User
        fields = ('email', 'profile', 'quantity',)

    def get_quantity(self, user):
        return len(user.email)

    ...

Basically, you modify Meta, but not the actual model, to add an extra quantity field to the output. You define this field as a SerializerMethodField. The serializer will invoke the method get_quantity to get the value of the field. In the example, the quantity is returned equal to the length of the email address of the user. This is useful in general for computed fields. These derived fields are automatically read-only and will be ignored on PUT and POST.

Reference is here.

damix911
  • 4,165
  • 1
  • 29
  • 44