2

I am trying to make models and serializers that allow GET and POST

The GET will allow the client to see a list of all Users, and will show info like first name, last name, etc, but not access_token

However, the POST just needs the access_token and can pull all info like first name, last name, etc from Facebook.

How can I express and code this assymetric nature of get and post in the serializer

serializers.py

class UserSerializer(serializers.HyperlinkedModelSerializer):
    """
    User Serializer
    """

    class Meta:
        model = models.User
        fields = ('id', 'username', 'first_name', 'last_name', 'image_url', 'activities', 'url', 'access_token')

views.py

class UserViewSet(viewsets.ModelViewSet):
    """
    List all users - this should be taken out as it would never be used in app, and we wont want this as well, as app can only view friend details
    Gives details of an user - this should stay
    """
    queryset = models.User.objects.all()

    serializer_class = UserSerializer
Cœur
  • 37,241
  • 25
  • 195
  • 267
dowjones123
  • 3,695
  • 5
  • 40
  • 83
  • you mention, `POST` can pull all info like first name, last name, etc from Facebook. but to my understanding, you don't POST when you want to get the information – Yeo Jul 12 '14 at 15:01
  • Thanks, I meant, as long as the server (the API end point generator) receives the access_token passed to it via POST at /user , it can retrieve all info from facebook on its own using that – dowjones123 Jul 12 '14 at 15:02
  • unfortunately, `POST` is meant for creation in RESTful API. So, I would suggest that if you want to retrieve all info from facebook without creating anything new, then make a `GET` request with an access_token passed to the query parameters or HTTP Headers – Yeo Jul 12 '14 at 15:09

1 Answers1

4

Any of these options:

  • Use read_only on fields that you don't want the user to be able to supply on creation.
  • Either override get_queryset and return a different serializer for GET vs POST.
  • Write the retrieve() and create() methods on the ViewSet explicitily.

However, the POST just needs the access_token and can pull all info like first name, last name, etc from Facebook.

You'll probably need a custom restore_object on the serializer to pull that info in.

Tom Christie
  • 33,394
  • 7
  • 101
  • 86
  • Thanks a lot Tom, that helped. I figured out the same from the docs as well. Also, thanks for the amazing thing the DRF is. Have posted an allied question here : http://stackoverflow.com/questions/24738438/suppressing-save-of-object-in-post-django-rest-framework – dowjones123 Jul 14 '14 at 14:08