简体   繁体   中英

Use existing ModelSerializer with JSONResponse

I have a Twitter authentication view that doesn't use a viewset so the auth can be handled on the backend. The view takes in the oauth_token & uses Twython to get the profile & create a Twitter model.

Currently I just return status 201 on success, but to alleviate the need for another request after creation, I'd like to return the created model. I have a TwitterSerializer already which defines the fields that I want to include, so I'd like to be able to reuse this if possible.

TwitterSerializer

class TwitterSerializer(serializers.ModelSerializer):

    class Meta:
        model = Twitter
        fields = (
            "id",
            "twitter_user_id",
            "screen_name",
            "display_name",
            "profile_image_url",
        )

When I try to use this, I get the error that Instance of TwitterSerializer is not JSON serializable .

            serialized = TwitterSerializer(instance=twitter)
            return JsonResponse({ "created": serialized })

I could return a serialized instance of the model using serializers.serialize()

            serialized = serializers.serialize('json', [twitter, ])
            serialized = serialized[0]
            return JsonResponse({ "created": serialized })

I could pass the fields kwarg to serialize() but I don't want to have to repeat myself if I don't have to. So would it be possible to re-use my TwitterSerializer in this case? I'm having trouble finding a direct answer since most docs assume you'll be using a ViewSet when using serializerss understandably, and this feels like an edge case. I'm open to suggestions for refactoring this approach as well!

After serialization, you can get your data using data attribute of serializer like this.

serialized = TwitterSerializer(instance=twitter)
return JsonResponse({ "created": serialized.data })

You should use Django rest Response instead of JsonResponse like this

from rest_framework response
serialized = TwitterSerializer(instance=twitter)
return response.Response({ "created": serialized.data })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM